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
Linda HamiltonOriginal
2024-11-28 19:22:10198browse

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);

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

[[
    "Afghanistan",
    32,
    13
], [
    "Albania",
    32,
    12
]]

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!

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