Home >Backend Development >PHP Tutorial >How to Encode Arrays with Non-Consecutive Numeric Keys as Arrays in JSON?

How to Encode Arrays with Non-Consecutive Numeric Keys as Arrays in JSON?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-12 18:03:02392browse

How to Encode Arrays with Non-Consecutive Numeric Keys as Arrays in JSON?

Encoding Arrays with Numeric Keys as Arrays

When encoding an array using json_encode(), an array with consecutive numeric keys will be serialized as an array in JSON. However, when the keys are non-consecutive, the resulting JSON string becomes an object with the keys replaced by strings representing their original values.

Solution: Using array_values()

To resolve this issue and obtain an array in JSON, we can leverage the array_values() function in PHP. It removes the original array keys and replaces them with zero-based consecutive numbers.

Example:

// Array with non-consecutive numeric keys
$array = [
    2 => ['Afghanistan', 32, 13],
    4 => ['Albania', 32, 12]
];

// Remove original keys using array_values()
$output = array_values($array);

// Encode the modified array as JSON
$json = json_encode($output);

// Result:
// [[Afghanistan, 32, 13], [Albania, 32, 12]]

By utilizing array_values(), we preserve the original values and structure of the array while ensuring it is serialized as an array in JSON.

The above is the detailed content of How to Encode Arrays with Non-Consecutive Numeric Keys as Arrays in JSON?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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