我是新來的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? –