使用PHP创建JSON对象的样式

时间:2016-04-18 22:47:55

标签: php json

我的JSON目前看起来像这样

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

我希望它看起来像这样

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

它是在这个php脚本中创建的,但我不确定如何以编程方式将customer属性添加到每个JSON对象。请帮忙吗?

//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;

1 个答案:

答案 0 :(得分:1)

//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;