PHP Array to JSON Array using json_encode();

Ryan Brodie picture Ryan Brodie · Jul 30, 2012 · Viewed 422k times · Source

I've encoded an Array I've made using the inbuilt json_encode(); function. I need it in the format of an Array of Arrays like so:

[["Afghanistan",32,12],["Albania",32,12]]

However, it is returning as:

{"2":["Afghanistan",32,12],"4":["Albania",32,12]}

How can I remove these row numbers without using any Regex trickery?

Answer

Michael Berkowski picture Michael Berkowski · Jul 30, 2012

If the array keys in your PHP array are not consecutive numbers, json_encode() must make the other construct an object since JavaScript arrays are always consecutively numerically indexed.

Use array_values() on the outer structure in PHP to discard the original array keys and replace them with zero-based consecutive numbering:

Example:

// Non-consecutive 3number keys are OK for PHP
// but not for a JavaScript array
$array = array(
  2 => array("Afghanistan", 32, 13),
  4 => array("Albania", 32, 12)
);

// array_values() removes the original keys and replaces
// with plain consecutive numbers
$out = array_values($array);
json_encode($out);
// [["Afghanistan", 32, 13], ["Albania", 32, 12]]