0

I'm trying to encode a two-dimensional PHP array to JSON with json_encode() and I'm having a problem:

My array looks like this:

$array = array( array( 1325368800, 6898 ) );

When I encode it to JSON using json_encode(), the output looks like this:

  'data' : [ 
          '0' : [  '0' : '1325368800',      '1' : '6898' ]
           ]

I would like to get rid of the automatically generated integer keys and have it like this:

'data':  [ [ '1325368800', '6898' ] ]

Any tips?

4
  • 3
    It doesn't for me. Commented Jan 18, 2012 at 0:45
  • What's wrong with [ "0": [ "0: "123", "1": "123" ] ]? Commented Jan 18, 2012 at 0:45
  • Are you absolutely sure this is all the code you have and you don't get that output: <?php $array = array( array( 123, 123 ) ); echo json_encode($array); ?> ? Commented Jan 18, 2012 at 0:46
  • because Highcharts doesn't seem to like the generated integers (enough question marks?:) Commented Jan 18, 2012 at 1:04

1 Answer 1

2

This can only happen if you give the JSON_FORCE_OBJECT flag to json_encode (live demo):

echo json_encode(array(array( 123, 123 )));
// outputs [[123,123]]

echo json_encode(array(array( 123, 123 )), JSON_FORCE_OBJECT);
// outputs {"0":{"0":123,"1":123}}

Make sure the second argument of json_encode is not set, or set to a value generated by ORing JSON_* constants together.

If, however, the data is an associative array, you can use array_values to get a JSON array instead of a JSON object:

$assocData = array('0' => array('0' => 123, '1'=>123));
$arrayData = array_map('array_values', array_values($assocData));
echo json_encode($arrayData);

By the way, the JSON output you cited is invalid, since it uses square brackets ([]) for objects, and misses a quote after "0.

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

5 Comments

I have hard time believing you could get json_encode to literally output [ "0": [ "0: "123", "1": "123" ] ] no matter what. It is even missing a quote for crying out loud.
Thanks for pointing it out Esailja, I was giving a simplified example. I modified the question to point out the problem with actual data.
@supertopi my point still stands even after your edit. Reproduce in codepad.viper-7.com
@supertopi It's always a good idea to give a reproducible example. The current version is better, but still not valid php. I updated this answer with a solution for a similar input.
Thanks phihag and Esaijlija for pointing out the encoding. With your answers I managed to trace the problems cause (which was in fact with the JavaScript JSON parser :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.