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

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

Linda Hamilton
Linda HamiltonOriginal
2024-11-12 06:52:01757browse

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

Creating an Array String with json_encode()

When encoding an array using json_encode(), numeric keys can sometimes lead to the resulting JSON string containing an object instead of an array. This issue arises because JavaScript arrays require consecutive numerical indexing.

To resolve this problem without resorting to regex manipulation, utilize array_values() on the outer array structure. This function eliminates the original keys and replaces them with zero-based consecutive numbering. Here's an example:

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

// Remove original keys and create consecutive numbers
$out = array_values($array);

// Encode the modified array
echo json_encode($out);
// Output: [[Afghanistan, 32, 13], [Albania, 32, 12]]

This approach ensures that the encoded JSON string is an array of arrays, as expected.

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