duangu8264 2012-05-06 16:38
浏览 59

JSON - 使用PHP的push_array

can someone please explain to me why the first one is working and the second one not? The result is in the second example simply "1".

1.

    $c = 0;
    $list = array();
    foreach ($places as $place) {
        $arr = array();
        $arr[0] = get_object_vars($place);
        $list[$c] = $arr;
        $c++;
    }
    echo json_encode(array("status" => "true", "list" => $list));

2.

    $list = array();
    foreach ($places as $place) {
        array_push($list, get_object_vars($place));
    }
    echo json_encode(array("status" => "true", "list" => $list));

Sample data for both code samples:

$places = array();

$place = new StdClass;
$place->name = 'first';
$place->location = array('x' => 0.0, 'y' => 0.0);
$places[] = $place;

$place = new StdClass;
$place->name = 'Greenwich Observatory';
$place->location = array('x' => 51.4778, 'y' => 0.0017);
$place->elevation = '65.79m';
$places[] = $place;
  • 写回答

1条回答 默认 最新

  • duankuixi1930 2012-05-06 16:44
    关注

    In the first case you are adding a key value pair to the array, in the second case just the value. I believe just adding the value SHOULD in fact work, but maybe

    foreach ($places as $place) {
        array_push($list, array( 0 => get_object_vars($place) );
    }
    

    will work better?

    评论

报告相同问题?

悬赏问题

  • ¥15 java报错:使用mybatis plus查询一个只返回一条数据的sql,却报错返回了1000多条
  • ¥15 Python报错怎么解决
  • ¥15 simulink如何调用DLL文件
  • ¥15 关于用pyqt6的项目开发该怎么把前段后端和业务层分离
  • ¥30 线性代数的问题,我真的忘了线代的知识了
  • ¥15 有谁能够把华为matebook e 高通骁龙850刷成安卓系统,或者安装安卓系统
  • ¥188 需要修改一个工具,懂得汇编的人来。
  • ¥15 livecharts wpf piechart 属性
  • ¥20 数学建模,尽量用matlab回答,论文格式
  • ¥15 昨天挂载了一下u盘,然后拔了