PHP数组到JSON阵列使用json_en code(); [英] PHP Array to JSON Array using json_encode();
问题描述
我有恩codeD使用内置的 json_en code()我做了一个数组;
功能。我需要它在阵列这样一个数组的格式为:
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]]
然而,可以为返回:
However, it is returning as:
["2":["Afghanistan",32,12],"4":["Albania",32,12]]
我怎么能不使用任何弄虚作假的正则表达式删除这些行号?
How can I remove these row numbers without using any Regex trickery?
推荐答案
如果你的PHP数组的数组键是不连续的数字, json_en code()
的必须的让对方构造一个对象,因为JavaScript数组始终是连续数字索引。使用 array_values()
上在PHP外部结构丢弃原来的数组键和从零开始连续编号替换它们:
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. 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 number 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]]
这篇关于PHP数组到JSON阵列使用json_en code();的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!