Ryan Brodie Ryan Brodie - 1 year ago 126
PHP Question

PHP Array to JSON Array using json_encode();

I've encoded an Array I've made using the inbuilt

function. I need it in the format of an Array of Arrays like so:


However, it is returning as:


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

Answer Source

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:


// Non-consecutive number 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);
// [["Afghanistan",32,13],["Albania",32,12]]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download