1
$my_array = array(
        0 => array(
                1,
                2,
                3,
            ),
        1 => array(
                1,
                2,
                3,
            ),
        2 => array(
                1,
                2,
                3,
            ),
    );
echo json_encode($my_array);

Result is this:

[[1,2,3],[1,2,3],[1,2,3]]

I thought the output should be a string of json,but here outputs a pure array,why?In other words,the result should be quoted,but why this is not.

7
  • That is a string of JSON. What were you expecting, specifically? Commented Sep 27, 2014 at 2:27
  • 1
    it may look like a shorthand array version, but yes, its still also json Commented Sep 27, 2014 at 2:29
  • when I encode one dimensional array,it is like this { "if": "foo" },but this is enclosed with square brackets,also not quoted,is this json? Commented Sep 27, 2014 at 2:31
  • @user7031 json_encode sees an array with string keys as an object, and JSON syntax surrounds objects with curly {} braces. The array in your question has only numeric keys, so it remains a JSON array with square [] brackets, and the keys remain unquoted. Look at meda's answer if you want to always encode as objects. Commented Sep 27, 2014 at 2:35
  • @wavemode when I quote the index,that became string keys,but json_encode still treated it as pure array,only 'JSON_FORCE_OBJECT' param can make the change? Commented Sep 27, 2014 at 2:43

1 Answer 1

3

Use JSON_FORCE_OBJECT with json_encode()

echo json_encode($my_array, JSON_FORCE_OBJECT);

Program Output

{"0":{"0":1,"1":2,"2":3},"1":{"0":1,"1":2,"2":3},"2":{"0":1,"1":2,"2":3}}

DEMO

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

3 Comments

that works,thanks,but what type of result I am having out there in the question?Is that a json too?
yes this is valid json as an array of array , this happens because you passed plain arrays (all integer) . try switching to words and you will notice the differnce
@user7031 did I answer your question or should I expand?

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.