Home >Backend Development >PHP Tutorial >How to Encode Arrays with Numeric Keys as an Array String in JSON?
When encoding arrays with numeric keys using json_encode(), you might encounter the issue of receiving an object string rather than an array string. This is because JSON arrays can only have consecutive numeric indices.
To address this, we must ensure that the original array keys are consecutive numbers. We can use array_values() to remove the original keys and replace them with consecutive indices:
// Input array with non-consecutive keys $array = [ 2 => ['Afghanistan', 32, 13], 4 => ['Albania', 32, 12] ]; // Remove original keys and replace with consecutive indices $out = array_values($array); // Encode the modified array $encoded = json_encode($out);
The encoded string will now be in the desired array format:
[[ "Afghanistan", 32, 13 ], [ "Albania", 32, 12 ]]
The above is the detailed content of How to Encode Arrays with Numeric Keys as an Array String in JSON?. For more information, please follow other related articles on the PHP Chinese website!