Home >Backend Development >PHP Tutorial >How to Encode a PHP Array with Non-Consecutive Numeric Keys as JSON Array?
When encoding an array using json_encode(), numeric keys can sometimes lead to the resulting JSON string containing an object instead of an array. This issue arises because JavaScript arrays require consecutive numerical indexing.
To resolve this problem without resorting to regex manipulation, utilize array_values() on the outer array structure. This function eliminates the original keys and replaces them with zero-based consecutive numbering. Here's an example:
// Non-consecutive numeric keys in a PHP array $array = array( 2 => array("Afghanistan", 32, 13), 4 => array("Albania", 32, 12) ); // Remove original keys and create consecutive numbers $out = array_values($array); // Encode the modified array echo json_encode($out); // Output: [[Afghanistan, 32, 13], [Albania, 32, 12]]
This approach ensures that the encoded JSON string is an array of arrays, as expected.
The above is the detailed content of How to Encode a PHP Array with Non-Consecutive Numeric Keys as JSON Array?. For more information, please follow other related articles on the PHP Chinese website!