我在将json数组连接到json对象时遇到问题
我运行查询以获取有关所选部件的详细信息,该部件仅返回一个结果(预期)。 然后我运行另一个查询来查找与第一个父部件相关的任何部件。这可能不返回任何或多个相关部分。 我希望我的最终输出看起来像这样:
{
"partCode": "P1",
"description": "The Parent Part",
"active": "1",
"partType": "1",
"partGroup": "BLR",
"qty": "1",
"page": "boiler",
"relatedParts": [
{
"partCode": "P2",
"description": "some related part",
"active": "1",
"partType": "1",
"partGroup": "BLR",
"qty": "1"
},
{
"partCode": "P3",
"description": "Another related part",
"active": "1",
"partType": "1",
"partGroup": "BLR",
"qty": "1"
}
]
}
如何将相关的parts []数组添加到json {}对象中?
我的疑问是:
//parent part
$query= "SELECT * FROM `parts`
INNER JOIN `partPrice` ON `parts`.`partCode` = `partPrice`.`partCode`
WHERE `parts`.`partCode` = '$part' AND `partPrice`.`active` = 1;";
$result = mysql_query($query);
if (!$result) {
die("Invalid query: " . mysql_error());
}
$json=array();
$relatedParts=array();
if (mysql_num_rows($result)>0){
while($row=mysql_fetch_assoc($result)){
$json[]=$row;
$json['relatedParts']=$relatedParts;
}
}
//get MANADTORY related parts
$query= "SELECT parts.*
FROM
partAssociation
INNER JOIN parts ON partAssociation.childPart = parts.partCode
WHERE
partAssociation.parentPart = '$part' AND
partAssociation.association = 'Requires';";
$result = mysql_query($query);
if (!$result) {
die("Invalid query: " . mysql_error());
}
$json2=array();
if (mysql_num_rows($result)>0){
while($row=mysql_fetch_assoc($result)){
$json2[]=$row;
}
}
$json['relatedParts']=$json2;
echo json_encode( $json);
编辑: 找到一个可能不完美但有效的解决方案; 首先获取相关记录,然后将该结果添加到父记录中 仍然会对任何更加光滑的方式感兴趣。
//get MANDATORY related parts
$query2 = "SELECT parts.*
FROM
partAssociation
INNER JOIN parts ON partAssociation.childPart = parts.partCode
WHERE
partAssociation.parentPart = '$part' AND
partAssociation.association = 'Requires';";
//set the holders
$json=array();
$relatedParts=array();
//get any related records first
$resultRP = mysql_query($query2);
if (!$resultRP) {
die("Invalid query: " . mysql_error());
}
if (mysql_num_rows($resultRP)>0){
while($row=mysql_fetch_assoc($resultRP)){
$relatedParts[]=$row;
}
}
//get parent record
$result = mysql_query($query1);
if (!$result) {
die("Invalid query: " . mysql_error());
}
if (mysql_num_rows($result)>0){
while($row=mysql_fetch_assoc($result)){
$row['relatedParts']=$relatedParts;
$json[]=$row;
}
}
echo json_encode($json);