创建具有关联数组键和数字数组值的数组PHP [英] Create an array with associative array keys and numeric array values PHP
问题描述
我正在尝试合并两个数组.关联的一个和一个数字数组. $new_array = array_combine($array1, $array2)
.但这是从数组1中获取值并将其设置为新数组的键,这就是本意.
I am trying to combine two arrays. An associative one and a numeric array. $new_array = array_combine($array1, $array2)
. But it is taking the values from array one and setting them as the keys for the new array, which is what is meant meant to do.
但是我需要将$ array1的键用作$ new_array的键,将$ array2的值用作$ new_array的值.我还研究了将$ array2的值合并到$ array1中,但是由于数组不共享相同的键,因此无法正常工作.
But I need to use the keys of $array1 to be the keys of $new_array and the values of the $array2 to be the values of the $new_array. I also looked into merging the values of $array2 to $array1 but it does not work properly as the arrays don't share the same keys.
这里是一个例子.
$array1 = "fname" => "NULL", "lname" => "NULL", "id" => "NULL";
$array2 = "john", "smith", "11123";
$new_array = "fname" => "john" , "lname" => "smith", id => "11123";
我正在考虑使用此array_combine(array_flip($array1), $array2);
但是array_flip不能使用NULL;
But array_flip can't work with NULL;
推荐答案
使用 array_flip
像这样:
Use array_keys
instead of array_flip
like so:
$array1 = ["fname" => "NULL", "lname" => "NULL", "id" => "NULL"];
$array2 = ["john", "smith", "11123"];
$new_array = array_combine(array_keys($array1), $array2);
print_r($new_array);
输出:
Array
(
[fname] => john
[lname] => smith
[id] => 11123
)
这篇关于创建具有关联数组键和数字数组值的数组PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!