I have a problem joining a json array into a json object
I run a query to get detail about a selected part which returns only one result (expected). I then run another query to find any parts that are related to the first parent part. this may return none or multiple associated parts. I want my final output to look like this:
{
"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"
}
]
}
How do add the related parts[] array into the json{} object?
My queries are:
//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);
EDIT: Found a solution probably not perfect but works; Getting the related records first then adding that result to the parent record Would still be interested in any slicker ways of doing this.
//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);