如何将数组转换为此json模式?

时间:2018-12-31 03:25:25

标签: php

我有类似这样的数组

Array
(
     [0] => Array
        (
            [product_id] => 13
            [unit] => 1
            [price] => 20.0000
            [total] => 20.0000
        )

    [1] => Array
        (
            [product_id] => 15
            [unit] => 2
            [price] => 30.0000
            [total] => 10.0000 
        )

)

我被迫按照以下模式将上面的数组转换为“ ProductList”

array(
     "UserID" => 2,
     "ProductList" => [
         {
             "ProductID"=> 13,
             "Price"=> 20.0000
         }, 
         {
             "ProductID"=> 15,
             "Price"=> 30.0000
         }
     ]
)

我尝试过这样:

$products = [];
foreach($items as $item) {
    if(!empty($item['product_id'])) {
        $product = '{"ProductID"=>' . $item['product_id'] . '}';
        $products[] = $product;
    }
}

但不是预期的结果。

2 个答案:

答案 0 :(得分:0)

您正在寻找json_encode()http://php.net/manual/en/function.json-encode.php

将数组分配给变量,例如$products,然后只需编写json_encode($products)即可达到所需的结果。

答案 1 :(得分:0)

尝试一下

$prodlist = array();
$x = 0;
foreach($arrs as $arr) {
    //if ($arr['product_id'] == "" && $arr['price'] == "") continue;
    $prodlist[$x]['Price'] = $arr['price'];
    $prodlist[$x]['ProductID'] = $arr['product_id'];
    $x += 1;
}
$arr2return['user_id'] = $user_id;
$arr2return['ProductList'] = $prodlist;
json_encode($arr2return);