john john - 7 months ago 11
PHP Question

create style of JSON object with PHP

my JSON currently looks like this

{
"customers":
[
{
"customer_id":3,
"customer_name":"Rick",
"Address":"333 North Road"
},
{
"customer_id":4,
"customer_name":"Robby",
"Address":"444 North West Road"
}
]
}


and I would like it to look like this

{
"customers":
[
{
"customer":
{
"customer_id":3,
"customer_name":"Rick",
"Address":"333 North Road"
}
},
{
"customer":
{
"customer_id":4,
"customer_name":"Robby",
"Address":"444 North West Road"
}
}
]
}


It is being created in this php script but I'm unsure how to add the customer attribute to each JSON object programmtically. help please?

//populate results
$json = array();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
$array = array(
'customer_id' => $row['CustomerID'],
'customer_name' => $row['Name'],
'Address' => $row['Address']
);
array_push($json, $array);
foreach ($row as $r) {

}
}

$jsonstring = '{"customers":'. json_encode($json). "}";
return $jsonstring;

Answer
//populate results
$json = array();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    $array = array("customer" => array(    // <-- change is here
               'customer_id' => $row['CustomerID'],
               'customer_name' => $row['Name'],
               'Address' => $row['Address']
            )
        );
    array_push($json, $array);
  foreach ($row as $r) {

  }
}

$jsonstring = '{"customers":'. json_encode($json). "}";
return $jsonstring;