1

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;
5
  • Why don't just do : $list[] = get_object_vars($place); ? Commented May 6, 2012 at 16:45
  • In 2. you are missing a ). Other than that, it should work fine. Commented May 6, 2012 at 16:56
  • @BartoszGrzybowski Well, yes, that's basically the same. Why would it make a difference? Commented May 6, 2012 at 16:58
  • It works with this code: $list[] = array(get_object_vars($place)); Commented May 6, 2012 at 17:32
  • Sample code should be complete, concise and representative. Without sample data, the code is incomplete. Also, what exactly do you mean by the second "not working" (an almost meaningless phrase)? What do you expect, and how is that different from what you get? Commented May 6, 2012 at 17:43

1 Answer 1

1

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?

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.