1

有人可以向我解释为什么第一个有效而第二个无效?结果在第二个示例中只是“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));

两个代码示例的示例数据:

$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;
4

1 回答 1

1

在第一种情况下,您将键值对添加到数组中,在第二种情况下只是值。我相信只是添加价值实际上应该有效,但也许

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

会更好吗?

于 2012-05-06T16:44:03.617 回答