When encoding an array with numeric keys using the json_encode() function in PHP, the result is often an object string with keys rather than an array string. This can be problematic when expecting an Array of Arrays format.
Problem Explanation:
In JavaScript, arrays require consecutive numeric keys. json_encode() will output an object if the keys in the PHP array are not consecutive numbers.
Solution:
To resolve this issue without using regex, we can utilize the array_values() function to discard the original array keys and replace them with zero-based consecutive numbering. This ensures that the encoded result is an array string.
Example:
// Non-consecutive numeric keys in PHP array $array = array( 2 => array("Afghanistan", 32, 13), 4 => array("Albania", 32, 12) ); // Remove original keys with array_values() $out = array_values($array); // Encode the resulting array $json = json_encode($out); // Output: [["Afghanistan", 32, 13], ["Albania", 32, 12]]
By using array_values(), we obtain the desired Array of Arrays format in JSON and avoid the object format with non-consecutive numeric keys.
The above is the detailed content of How to Encode a PHP Array with Non-Consecutive Numeric Keys as a JSON Array?. For more information, please follow other related articles on the PHP Chinese website!