How to Ensure JSON Serialization of Arrays with Non-Consecutive Keys?

Mary-Kate Olsen
Release: 2024-11-11 06:03:03
Original
976 people have browsed it

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]]]
Copy after login

This modification will ensure that the serialized JSON output is an array of arrays, as desired:

[["Afghanistan", 32, 13], ["Albania", 32, 12]]
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template