我正在使用以下代码将两个数组合并为一个json结果。但是只得到第一个索引。代码中是否有错误,或者有人可以建议一种替代方法来获得相同的结果。
$array1 = $_POST['array1'];
$array2 = $_POST['array2'];
$jsonArray = array();
foreach (array_combine( $array1, $array2 ) as $name => $value) {
$jsonArray[] = array('name' => $name, 'value' => $value);
}
echo $json = json_encode($jsonArray);
$_POST['array1'] = array(4) {
[0]=>
string(3) "day1"
[1]=>
string(3) "day2"
[2]=>
string(3) "day3"
[3]=>
string(3) "day4"
}
$_POST['array2'] = array(4) {
[0]=>
string(3) "item1"
[1]=>
string(3) "item2"
[2]=>
string(3) "item3"
[3]=>
string(3) "item4"
}
预期结果应该像
[{"name":"day1","value":"item1"},{"name":"day2","value":"item2"},{"name":"day3","value":"item3"}]
答案 0 :(得分:0)
尝试一下,
$arr1 = array('0' => 'day1', '1' => 'day2', '2' => 'day3', '3' => 'day4');
echo'<pre>';print_r($arr1);
$arr2 = array('0' => 'item1','1' => 'item2','2' => 'item3','3' => 'item4');
echo'<pre>';print_r($arr2);
echo'<pre>';print_r(array_combine($arr1, $arr2));
$newArray = array();
foreach(array_combine($arr1, $arr2) as $key => $value){
array_push($newArray, array('name'=> $key,'value'=>$value));
}
echo'<pre>';print_r($newArray);
echo json_encode($newArray);die;