Home >Backend Development >PHP Tutorial >How to Ensure JSON Serialization of Arrays with Non-Consecutive Keys?
Modifying Array Keys for JSON Serialization
When using the json_encode() function, arrays with numeric keys can be serialized as objects instead of arrays, leading to undesired output. This occurs when the array keys are non-consecutive.
To address this issue without resorting to regular expressions, consider utilizing array_values() on the outermost array structure. By calling array_values($array), you can discard the original array keys and replace them with zero-based consecutive numbers.
Example:
$array = [ 2 => ["Afghanistan", 32, 13], 4 => ["Albania", 32, 12] ]; $output = array_values($array); echo json_encode($output); // [[["Afghanistan", 32, 13], ["Albania", 32, 12]]]
This modification will ensure that the serialized JSON output is an array of arrays, as desired:
[["Afghanistan", 32, 13], ["Albania", 32, 12]]
The above is the detailed content of How to Ensure JSON Serialization of Arrays with Non-Consecutive Keys?. For more information, please follow other related articles on the PHP Chinese website!