简体   繁体   English

PHP JSON Array - 如何按相同的值修改 json 代码组

[英]PHP JSON Array - how to modify a json code Group by the same value

I grouped my table by objects with the same value with php foreach function我使用 php foreach 函数按具有相同值的对象对我的表进行分组

$data = json_decode($geo, true);
$out = [];
foreach($data as &$element) {
     $out[$element['id']][] = [
        'lng' => $element['lng'],
        'lat' => $element['lat'],
        'time' => $element['time']
    ];
};
$geo = json_encode($out);

later I got this result后来我得到了这个结果

"[{

"1":[{"lng":134.94157,"lat":36.871337,"time":1502159287}],

"2":[{"lng":134.94157,"lat":34.598832,"time":1502211838}],

"3":[{"lng":131.225,"lat":37.101667,"time":1502144333},{"lng":131.24,"lat":37.123333,"time":1502144343}]
}]"

now I want my data to be like this现在我希望我的数据是这样的

[

[{"lng":134.94157,"lat":36.871337,"time":1502159287}],

[{"lng":134.94157,"lat":34.598832,"time":1502211838}],

[{"lng":131.225,"lat":37.101667,"time":1502144333},{"lng":131.24,"lat":37.123333,"time":1502144343}]

]

How can I do this?我怎样才能做到这一点?

First, json_decode() your initial JSON data.首先, json_decode()您的初始 JSON 数据。 Then, move to the first index in the decoded data and only pick values of the array's values skipping the keys with the help of array_values() .然后,移动到解码数据中的第一个索引,并在array_values()的帮助下仅选择跳过键的数组值的值。

<?php

$prev_json = '[{"1":[{"lng":134.94157,"lat":36.871337,"time":1502159287}],"2":[{"lng":134.94157,"lat":34.598832,"time":1502211838}],"3":[{"lng":131.225,"lat":37.101667,"time":1502144333},{"lng":131.24,"lat":37.123333,"time":1502144343}]}]';

$data = json_decode($prev_json,true);

$new_json = json_encode(array_values($data[0]));

echo $new_json;

Demo: https://3v4l.org/bFmYn演示: https : //3v4l.org/bFmYn

Update: Looking at your updated code, you could remove the $element['id'] from $out[$element['id']] and make it as $out[] = [..rest of your code..] and it should work.更新:查看更新后的代码,您可以从$out[$element['id']]删除$element['id'] $out[$element['id']]并将其设为$out[] = [..rest of your code..]它应该工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM