我是新来的PHP,并试图实现一种方式来从一个表输出数据,以对应于另一个表中的JSON对象。表中的项目与另一个表中的特定JSON不匹配:PHP?
目前这是主要的表:
这是含有是假设在主表对应于每个“ID”项所述第二表:
例如,在第二个表中,culturevillage_id
对应于主表中的id
。因此,使用id = 1
的JSON应输出6个项目。
这是我试图执行代码:
$sql = "select * from main_table";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
$jsonData = array();
$rowCount = $result->num_rows;
$index = 1;
while($row =mysqli_fetch_assoc($result))
{
$sqlnew = "select * from secondary_table where culturevillage_id=" .$row['id']. "" ;
$resultnew = mysqli_query($connection, $sqlnew) or die("Error in Selecting " . mysqli_error($connection));
//create an array
$jsonData = array();
$rowCountnew = $resultnew->num_rows;
$indexnew = 1;
//echo $rowCount;
if ($rowCountnew >0)
{
while($rownew =mysqli_fetch_assoc($resultnew))
{
$imageString[$indexnew] = array("normal_res_link" => $rownew['normal_res_link']);
++$indexnew;
}
}
echo '"item'.$index.'":';
echo json_encode(array("id" => intval($row['id']),"english_name" => $row['english_name'], "vietnamese_name" => $row['vietnamese_name'], "images" =>$imageString));
if ($rowCount != $index)
{
echo ',';
}
++$index;
}
echo ' }'
不过,我得到以下输出:
{
"item1": {
"id": 1,
"english_name": "Ben Thanh Market",
"vietnamese_name": "Cho Ben Thanh",
"images": {
"1": {
"normal_res_link": "id=1"
},
"2": {
"normal_res_link": "id=1"
},
"3": {
"normal_res_link": "id=1"
},
"4": {
"normal_res_link": "id=1"
},
"5": {
"normal_res_link": "id=1"
},
"6": {
"normal_res_link": "id=1
}
}
},
"item2": {
"id": 3,
"english_name": "One Pillar Pagoda",
"vietnamese_name": "Chua Mot Cot",
"images": {
"1": {
"normal_res_link": "id=1"
},
"2": {
"normal_res_link": "id=1"
},
"3": {
"normal_res_link": "id=1"
},
"4": {
"normal_res_link": "id=1"
},
"5": {
"normal_res_link": "id=1"
},
"6": {
"normal_res_link": "id=1"
}
}
},
"item3": {
"id": 4,
"english_name": "Hung King Temple",
"vietnamese_name": "Den Hung"
"images": {
"1": {
"normal_res_link": "id=4"
},
"2": {
"normal_res_link": "id=4"
},
"3": {
"normal_res_link": "id=1"
},
"4": {
"normal_res_link": "id=1""
},
"5": {
"normal_res_link": "id=1"
},
"6": {
"normal_res_link": "id=1"
}
}
}
}
的item1
JSON的images
领域是正确的,应该有6个项目。但对于item2
,输出从item1
的图像数据中获取,而对于item3
,则从item1
的图像数据中获取剩余的4个项目。
正确的输出应该是item2
的图像字段应该是空的,item3
的图像字段应该只包含2个数据,根据辅助表中的数据。
我知道我的实现是错误的地方,但我不确定。
有人能指出我正确的方向吗?
你为什么不在这里使用JOIN? –