PHP - 如何向JSON编码数组添加更多对象

时间:2013-09-02 02:39:05

标签: php json

我在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"}

如何将这两个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 个答案:

答案 0 :(得分: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);

答案 1 :(得分: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 . ']';

答案 2 :(得分: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);

答案 3 :(得分:0)

$je --> your JSON Data...

$jn = json_decode($je,true);
  array_push($jn, array('city1' => 'City 1'),array('city2' => 'New City 2'));