0

我有 json 在 php 中编码,它的输出是这样的。

[{"city":"Asasqewq"},{"city":"New Brunswick"},{"city":"Jersey City"},{"city":"Summit"},{"city":"Edison"},{"city":"Hillside"},{"city":"East Orange"}]

{"city":"New City 1"},{"city":"New City 2"}

如何将这 2 个 json 数据对象合并为这样的输出?

 [{"city":"Asasqewq"},{"city":"New Brunswick"},{"city":"Jersey City"},{"city":"Summit"},{"city":"Edison"},{"city":"Hillside"},{"city":"East Orange"}, {"city":"New City 1"},{"city":"New City 2"}]
4

4 回答 4

1
$json_str = '[{"city":"Asasqewq"},{"city":"New Brunswick"},{"city":"Jersey City"},{"city":"Summit"},{"city":"Edison"},{"city":"Hillside"},{"city":"East Orange"}]
';

$json_arr = json_decode($json_str, true);

$json_arr[] = array('city' => 'NewCity1');
$json_arr[] = array('city' => 'NewCity2');

$json_str = json_encode($json_arr);
于 2013-09-02T02:43:26.297 回答
0

最简单的解决方案是使用substr

$json = '[{"city":"Asasqewq"},{"city":"New Brunswick"},{"city":"Jersey City"},{"city":"Summit"},{"city":"Edison"},{"city":"Hillside"},{"city":"East Orange"}]';
$new = '{"city":"New City 1"},{"city":"New City 2"}';
$json = substr($json,0,-1) . ',' . $new . ']';
于 2013-09-02T02:42:32.887 回答
0

在对数组进行编码之前,将 2 个城市添加到其中,然后对其进行编码。

$theArray[] = array("city"=>"New City 1");
$theArray[] = array("city"=>"New City 2");
$json = json_encode($theArray);

现在,如果您无权访问该对象,您可以对其进行解码,添加再次对其进行编码的项目。

$theArray = json_decode($json);
$theArray[] = array("city"=>"New City 1");
$theArray[] = array("city"=>"New City 2");
$json = json_encode($theArray);
于 2013-09-02T02:49:02.377 回答
0
$je --> your JSON Data...

$jn = json_decode($je,true);
  array_push($jn, array('city1' => 'City 1'),array('city2' => 'New City 2'));
于 2013-09-02T03:05:53.747 回答