我有一个像这样的数组
Array
(
[0] => [{"qty":"4023","discount":"-288.84000194072723"}]
[1] => [{"qty":"48","discount":"-1"}]
[2] => [{"qty":"305","discount":"0"}]
)
如何将这些数组转换为我的格式,如
[{"name":"qty","data":[4023,48,305]},{"name":"discount","data":[-288.84,-1,0]}]
如何解决这个问题?
答案 0 :(得分:1)
查看json_encode功能。
来自PHP.net的示例:
<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
?>
输出:
{"a":1,"b":2,"c":3,"d":4,"e":5}
答案 1 :(得分:1)
以下是完整解决方案(使用json_encode
和json_decode
):
$array = array(
'[{"qty":"4023","discount":"-288.84000194072723"}]',
'[{"qty":"48","discount":"-1"}]',
'[{"qty":"305","discount":"0"}]'
);
$new = array(
(object) array("name" => "qty", "data" => array()),
(object) array("name" => "discount", "data" => array())
);
foreach($array as $key => $value){
$object = json_decode($value)[0];
$new[0]->data[] = $object->qty ;
$new[1]->data[] = $object->discount ;
}
$desired_result = json_encode($new);
var_dump($desired_result);
用于测试的沙箱: Here