0

It must be a better way to do this? I want to get all documents from the sounds collection and output them with an array with objects in (using it for backbone.js). It cant be an object with objects in!

$sounds = iterator_to_array($db->sounds->find());

    $a = "[";

    foreach ($sounds as $id => $sound) {
        $a .= json_encode($sound) . ",";
    }

    //remove the last comma...
    $a = substr($a, 0, -1);
    $a .="]";

    echo $a;
3
  • How about echo json_encode(array_values($sounds)); ? Commented Apr 9, 2013 at 6:43
  • yea! this works great! could you explain what it does? Commented Apr 9, 2013 at 6:51
  • I'll post it as answer with explanation. Commented Apr 9, 2013 at 6:52

1 Answer 1

1

You could try:

$sounds = iterator_to_array($db->sounds->find());
echo json_encode(array_values($sounds));

array_values will return values of associated array as indexed array so json_encode will return json encoded string in a format you want (i.e. javascript array instead of javascript object).

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.