使用 json_encode() 编码数组时,数字键有时会导致生成的 JSON 字符串包含对象而不是一个数组。出现此问题的原因是 JavaScript 数组需要连续的数字索引。
要在不诉诸正则表达式操作的情况下解决此问题,请在外部数组结构上使用 array_values()。此功能消除了原来的键并用从零开始的连续编号代替它们。下面是一个示例:
// 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]]
此方法可确保编码的 JSON 字符串是数组的数组,正如预期的那样。
以上是如何将具有非连续数字键的 PHP 数组编码为 JSON 数组?的详细内容。更多信息请关注PHP中文网其他相关文章!