Home > Backend Development > PHP Tutorial > How to Encode Arrays with Numeric Keys as an Array String in JSON?

How to Encode Arrays with Numeric Keys as an Array String in JSON?

Linda Hamilton
Release: 2024-11-28 19:22:10
Original
204 people have browsed it

How to Encode Arrays with Numeric Keys as an Array String in JSON?

Resolving JSON Encoding of Arrays with Numeric Keys as an Array String

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:

Example:

// 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);
Copy after login

The encoded string will now be in the desired array format:

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

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!

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