从 PHP 中的多个数组创建多维数组
Create multidimensional array from multiple arrays in PHP
我有两个数组:
Array ( [0] => label [1] => data )
Array ( [0] => 1 [1] => 2 )
我需要将它们合并成一个数组,如下所示:
Array ( [0] => Array ( [label] => 1 [data] => 2 ) )
我试过:
for ($i=0; $i < count($inputs); $i++) {
$new = array($cols[$i] => $inputs[$i]);
$data[] = $new;
}
欢迎任何帮助 ;)
您可以简单地使用 array_combine:
Creates an array by using one array for keys and another for its
values
$arr1 = array(0 => 'label', 1 => 'data');
$arr2 = array(0 => 1, 1 => 2);
$arr3 = array_combine($arr1, $arr2);
print_r($arr3);
结果:
Array
(
[label] => 1
[data] => 2
)
如果你想使用循环,你可以这样做
$array1 = ['label', 'data'];
$array2 = [1, 2];
$array_merged = [];
foreach($array1 as $key => $value) {
$array_merged[$value] = $array2[$key];
}
var_dump($array_merged);
http://sandbox.onlinephpfunctions.com/code/c4e5bc71df53ebdafb0a54d43c3eadb4ea4cd241
我有两个数组:
Array ( [0] => label [1] => data )
Array ( [0] => 1 [1] => 2 )
我需要将它们合并成一个数组,如下所示:
Array ( [0] => Array ( [label] => 1 [data] => 2 ) )
我试过:
for ($i=0; $i < count($inputs); $i++) {
$new = array($cols[$i] => $inputs[$i]);
$data[] = $new;
}
欢迎任何帮助 ;)
您可以简单地使用 array_combine:
Creates an array by using one array for keys and another for its values
$arr1 = array(0 => 'label', 1 => 'data');
$arr2 = array(0 => 1, 1 => 2);
$arr3 = array_combine($arr1, $arr2);
print_r($arr3);
结果:
Array
(
[label] => 1
[data] => 2
)
如果你想使用循环,你可以这样做
$array1 = ['label', 'data'];
$array2 = [1, 2];
$array_merged = [];
foreach($array1 as $key => $value) {
$array_merged[$value] = $array2[$key];
}
var_dump($array_merged);
http://sandbox.onlinephpfunctions.com/code/c4e5bc71df53ebdafb0a54d43c3eadb4ea4cd241