Create an array with associative array keys and nu

2019-07-26 22:39发布

问题:

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.

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.

Here is an example.

$array1 = "fname" => "NULL", "lname" => "NULL", "id" => "NULL";

$array2 = "john", "smith", "11123";

$new_array = "fname" => "john" , "lname" => "smith", id => "11123";

I was thinking of using this array_combine(array_flip($array1), $array2);

But array_flip can't work with NULL;

回答1:

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);

Output:

Array
(
    [fname] => john
    [lname] => smith
    [id] => 11123
)

eval.in demo



回答2:

You could simply iterate and assign

  $i = 0;
  foreach( $array1 as $key=>$value){
    $new_array[$key]=> $array2[$i];
    $i++;
  }