简体   繁体   中英

How to combine an array of keys with corresponding values from another array?

I have 2 arrays

Array ( [1] => Manufacturer [2] => Location [3] => Hours [4] => Model ) 

and

Array ( [Manufacturer] => John Deere [Location] => NSW [Hours] => 6320 ) 

I need to combine them and associate the values from the first array( Manufacturer, Location, hours , Model) as names in the 2nd array and if a specific values from the first array doesn't find associative name in the 2nd array to associate empty . For the example the result that I need from the above arrays is an array like this

   Array ( [Manufacturer] => John Deere [Location] => NSW [Hours] => 6320 [Model] => ) 

If i use simple array_combine it says that PHP Warning: array_combine() [function.array-combine]: Both parameters should have equal number of elements

You can use a simple foreach loop:

$combined = array();
foreach ($keys as $key) {
    $combined[$key] = isset($values[$key]) ? $values[$key] : null;
}

Where $keys is your first array with the keys and $values is your second array with the corresponding values. If there is no corresponding value in $values the value will be null .

Assuming $array1 and $array2 in order as you listed them, I think this would work:

$newArray = array();
while (list(,$data) = each($array1)) {
  if (isset($array2[$data])) {
     $newArray[$data] = $array2[$data];
  } else {
     $newArray[$data] = "";
  }
}

Try array_merge() . This example appears to do what you want:

<?php
$keys = array( 1 => "Manufacturer", 2 => "Location", 3 => "Hours", 4 => "Model") ;
$canonical = array_combine(array_values($keys), array_fill(0, count($keys), null));

$data = array("Manufacturer" => "John Deere", "Location" => "NSW", "Hours" => 6320);

print_r(array_merge($canonical, $data));

If the array of keys is $array1, and the associative array with values is $array2:

$new_array = array_merge(array_fill_keys(array_flip($array1), ''), $array2));

This inverts your key array, filling it with '' values. Then when you merge the arrays, any duplicate keys will be overwritten by the second array, but unfilled keys will remain.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM