常见需求:把一个父栏目下的子栏目循环出来,每个子栏目下再显示最新的几篇内容。
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "test";
// 创建连接
$conn = new MySQLi($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
//一级菜单id
$pid = $_REQUEST['pid'];
$sql = "SELECT * FROM `master_class` WHERE pid=" . $pid;
//分类数据
$class_result = $conn->query($sql);
//最终数据json
$data_json = array();
//文章数据
$tmp_art=array();
//分类
$tmp_cla=array();
//有结果
if ($class_result->num_rows > 0) {
// while 输出数据
while ($row = $class_result->fetch_assoc()) {
//得到classid
$classid = $row['id'];
$article_sql = "SELECT * FROM `master_article` WHERE `classid`=" . $classid;
$tmp_cla['id']=$row['id'];
$tmp_cla['name']=$row['name'];
$tmp_cla['pid']=$row['pid'];
//查询文章数据
$article_result = $conn->query($article_sql);
if ($article_result->num_rows > 0) {
// while 输出数据
while ($r= $article_result->fetch_assoc()) {
$tmp=array('id'=>$r['id'],'name'=>$r['name'],'classid'=>$r['classid']);
$tmp_art[]=$tmp;
}
$tmp_cla['article']=$tmp_art;
$tmp_art=null;
}
$data_json[]=$tmp_cla;
}
} else {
echo "0 结果";
}
echo json_encode($data_json);
$conn->close();
?>