Home  >  Article  >  Backend Development  >  How to Encode a PHP Array with Non-Consecutive Numeric Keys as a JSON Array?

How to Encode a PHP Array with Non-Consecutive Numeric Keys as a JSON Array?

Susan Sarandon
Susan SarandonOriginal
2024-11-21 12:21:10722browse

How to Encode a PHP Array with Non-Consecutive Numeric Keys as a JSON Array?

Resolving JSON Object Output from Numeric Array in PHP Using json_encode()

When encoding an array with numeric keys using the json_encode() function in PHP, the result is often an object string with keys rather than an array string. This can be problematic when expecting an Array of Arrays format.

Problem Explanation:

In JavaScript, arrays require consecutive numeric keys. json_encode() will output an object if the keys in the PHP array are not consecutive numbers.

Solution:

To resolve this issue without using regex, we can utilize the array_values() function to discard the original array keys and replace them with zero-based consecutive numbering. This ensures that the encoded result is an array string.

Example:

// Non-consecutive numeric keys in PHP array
$array = array(
    2 => array("Afghanistan", 32, 13),
    4 => array("Albania", 32, 12)
);

// Remove original keys with array_values()
$out = array_values($array);

// Encode the resulting array
$json = json_encode($out);

// Output: [["Afghanistan", 32, 13], ["Albania", 32, 12]]

By using array_values(), we obtain the desired Array of Arrays format in JSON and avoid the object format with non-consecutive numeric keys.

The above is the detailed content of How to Encode a PHP Array with Non-Consecutive Numeric Keys as a JSON Array?. 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