我正在尝试将数组转换为 JSON格式!
[
[
["SNO",1],
["chartType","pie"],
["outputValues","rural_total_m,urban_total_m"],
["attributeId",10025],
["level","india"]
],
[
["SNO",2],
["chartType","column"],
["outputValues","total_m"],
["attributeId",10025],
["level","state"]
]
]
我有一个数组,因为 sql查询和php的 print_r()函数将其打印为 -
Array
(
[0] => Array
(
[SNO] => 1
[chartType] => pie
[outputValues] => rural_total_m,urban_total_m
[attributeId] => 10025
[level] => india
)
[1] => Array
(
[SNO] => 2
[chartType] => column
[outputValues] => total_m
[attributeId] => 10025
[level] => state
)
)
我如何获得上述格式? 谢谢!
答案 0 :(得分:1)
<强>更新强>
如果你想要这样的东西
[
[
["SNO",1],
["chartType","pie"],
["outputValues","rural_total_m,urban_total_m"],
["attributeId",10025],
["level","india"]
],[
["SNO",2],
["chartType","column"],
["outputValues","total_m"],
["attributeId",10025],
["level","state"]
]
]
然后使用此代码
让mock数组为$ result
$result = array(
array(
"SNO" => 1,
"chartType" => "pie",
"outputValues" => "rural_total_m,urban_total_m",
"attributeId" => 10025,
"level" => "india"
),
array(
"SNO" => 2,
"chartType" => "column",
"outputValues" => "total_m",
"attributeId" => 10025,
"level" => "state"
)
);
$return_array = array();
foreach ($result as $value) {
$temp_array = array();
foreach ($value as $key => $value) {
$temp_array[] = array($key,$value);
}
$return_array[] = $temp_array;
}
echo json_encode($return_array);
否则,如果您希望输出就像这样
[
["SNO",1],
["chartType","pie"],
["outputValues","rural_total_m,urban_total_m"],
["attributeId",10025],
["level","india"]
["SNO",2],
["chartType","column"],
["outputValues","total_m"],
["attributeId",10025],
["level","state"]
]
然后使用这个
$ return_array = array();
foreach ($result as $value) {
foreach ($value as $key => $value) {
$return_array[] = array($key,$value);
}
}
---------------------------------更新前--------- ------------------------------------------- 强>
不是最有效的解决方案,但会做到这一点!!
$array = array(7,4,2,8,4,1,9,3,2,16,7,12);
$alpha = 'a';
$retur_array = array();
foreach ($array as $value) {
$retur_array[] = array($alpha++ , $value);
}
json_encode($retur_array);
输出
[
["a",7],
["b",4],
["c",2],
["d",8],
["e",4],
["f",1],
["g",9],
["h",3],
["i",2],
["j",16],
["k",7],
["l",12]
]
答案 1 :(得分:1)
Yuor输入数组将数字作为键。您需要循环并将键更改为子数组中的值。
$new_array = array();
foreach ($array as $key => $val) {
$new_array[] = array("$key", $val);
}
echo json_encode($new_array);