I have the following php code,
我有以下PHP代码,
<?php
$first = array(1,2,3);
$last = array(4,5,6);
$k = 10;
echo json_encode(array('id' =>$k, 'name' => array( 'first' => $first, 'last' => $last)));
?>
I only get this result
我只得到这个结果
{"id":10,"name":{"first":[1,2,3],"last":[4,5,6]}}
but I want the following format, so that I can access the data in javascript like name.first and name.last
但我想要以下格式,以便我可以在javascript中访问数据,如name.first和name.last
{"id":10,"name":[{"first":1,"last":4},{"first":2,"last":5},{"first":3,"last":6}] }
can anyone help me out?
谁能帮我吗?
Thanks,
谢谢,
Pat
拍
2 个解决方案
#1
4
Use array_map to operate in the same time on the multiple arrays:
使用array_map在多个数组上同时运行:
$array = array_map(function ($first, $last) { return array("first" => $first, "last" => $last); }, $first, $last);
echo json_encode(array('id' =>$k, 'name' => $array));
#2
0
Sample code for a brute force solution for this:
针对此的暴力解决方案的示例代码:
$first = array(1,2,3);
$last = array(4,5,6);
$name = array();
for( $i = 0; $i < count($first); $i++) {
$name[$i]['first'] = $first[$i];
$name[$i]['last'] = $last[$i];
}
echo json_encode(array('id' =>$k, 'name' =>$name));
#1
4
Use array_map to operate in the same time on the multiple arrays:
使用array_map在多个数组上同时运行:
$array = array_map(function ($first, $last) { return array("first" => $first, "last" => $last); }, $first, $last);
echo json_encode(array('id' =>$k, 'name' => $array));
#2
0
Sample code for a brute force solution for this:
针对此的暴力解决方案的示例代码:
$first = array(1,2,3);
$last = array(4,5,6);
$name = array();
for( $i = 0; $i < count($first); $i++) {
$name[$i]['first'] = $first[$i];
$name[$i]['last'] = $last[$i];
}
echo json_encode(array('id' =>$k, 'name' =>$name));