如何从PHP表创建JSON

时间:2015-08-28 09:34:30

标签: php json mysqli

如何在php中创建这样的json;

[{"idorder":"34",
 "totalOrder":"55",
 "products":[{"idproduct":"5","price":"10"},{"idproduct":"4","price":"45"}]
}]

来自表mysql;

+---------+-----------+--------------+
| idorder | idproduct | priceproduct |
+---------+-----------+--------------+
|       1 |         4 |           45 |
|       1 |         5 |           10 |
+---------+-----------+--------------+

我当前的代码something.php;

    ...
$result = $conn->query($pendientesq);
$return_arr = array();
$productos = array();
$r1=$result->fetch_array();
$return_arr['idorder'] = $r1['idorder'];
$return_arr['totalOrder'] = '55';

//但是现在????如何使用多个产品创建子数组。

echo json_encode($return_arr);

2 个答案:

答案 0 :(得分:1)

你需要尝试这样的事情:

$r1=$result->fetch_array();
$return_arr['idorder'] = $r1['idorder'];
$return_arr['totalOrder'] = '55';
// suposse total products are 10

$product=10;
for($i=0;$i<product;$i++){
$return_arr['product'][] = array("idproduct"=>$i,"price"=>$i);//use your price and idproduct.
}

echo json_encode($return_arr);

答案 1 :(得分:0)

我不知道你的桌子是怎样的,因为你没有描述它 但我得到了例如&#34;命令&#34;带有idorder,idproduct,priceproduct字段的表 并编写了这段代码:

// $q = "SELECT * FROM orders WHERE idorder = 5"; // for single order
$q = "SELECT * FROM orders"; 
$result = $conn->query($q);
$orders = [];
while($record=$result->fetch_array()) {
  if(!isset($orders[$record['idorder']])) {
    $orders[$record['idorder']] = [];
    $orders[$record['idorder']]['idorder'] = $record['idorder'];
    $orders[$record['idorder']]['totalOrder'] = 0;
    $orders[$record['idorder']]['products'] = [];
  }

  $orders[$record['idorder']]['products'][] = ['idproduct' => $recrod['idproduct'], 
                                               'price'     => $record['priceproduct']];
  $orders[$record['idorder']]['totalOrder'] += $record['priceproduct'];
}

$orders = array_values($orders);

echo json_encode($orders);