问题描述
我已经使用内置的 json_encode();
函数对我制作的数组进行了编码.我需要像这样的数组数组格式:
I've encoded an Array I've made using the inbuilt json_encode();
function. I need it in the format of an Array of Arrays like so:
[["Afghanistan",32,12],["Albania",32,12]]
但是,它返回为:
{"2":["Afghanistan",32,12],"4":["Albania",32,12]}
如何在不使用任何正则表达式技巧的情况下删除这些行号?
How can I remove these row numbers without using any Regex trickery?
推荐答案
如果你的 PHP 数组中的数组键不是连续的数字,json_encode()
必须other 构造一个对象,因为 JavaScript 数组总是连续数字索引.
If the array keys in your PHP array are not consecutive numbers, json_encode()
must make the other construct an object since JavaScript arrays are always consecutively numerically indexed.
使用array_values()
在 PHP 中的外部结构上丢弃原始数组键并用从零开始的连续编号替换它们:
Use array_values()
on the outer structure in PHP to discard the original array keys and replace them with zero-based consecutive numbering:
// Non-consecutive 3number keys are OK for PHP
// but not for a JavaScript array
$array = array(
2 => array("Afghanistan", 32, 13),
4 => array("Albania", 32, 12)
);
// array_values() removes the original keys and replaces
// with plain consecutive numbers
$out = array_values($array);
json_encode($out);
// [["Afghanistan", 32, 13], ["Albania", 32, 12]]
这篇关于使用 json_encode() 将 PHP 数组转换为 JSON 数组;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!