简体   繁体   中英

Matching keys from one array to another and creating a new array with their values?

Hi I have two arrays the first one looks like this:

array(  
    00000 => array(  
                 0 => 123,
                 1 => 456,
                 2 => 789,  
               )
    11111 => array(  
                 0 => 987,  
                 1 => 654,  
                 2 => 321,  
               )

My second array looks like this:

array(  
    00000 => 'apples',  
    11111 => 'bananas',
)

What am trying to do is match the keys from the 1st array with the keys in array 2nd then if they match take the values of key pair value array of the first array and make them keys for a brand new array and the values of the second array make them values for the brand new array. Something like this:

array(  
    123 => 'apples',  
    456 => 'apples',  
    789 => 'apples',  
    987 => 'bananas',  
    654 => 'bananas',  
    321 => 'bananas',  
)

Any help thanks!

so im assuming u have 2 arrays (and you fixed second array to have unique keys)

$array3 = array (); //for the result
foreach ($array1 as $seg)
{

   foreach ($seg as $key)
   {
      $array3[$key] = $array2[$seg];
   }     
}

Try this

$array = array(
    "00000" => array(
                 0 => 123,
                 1 => 456,
                 2 => 789,
    ),
    "11111" => array(
                 0 => 987,  
                 1 => 654,  
                 2 => 321,  
    )
);

$arr = array(  
    "00000" => 'apples',  
    "11111" => 'bananas',
);

$array3 = array();
foreach ($array as $keyas => $segs)
{
    foreach ($segs as $key)
   {
       $array3[$key] = $arr[$keyas];
   }     
}
 echo "<pre>";
 print_r($array3);
 unset($array3);

Output :

Array
(
    [123] => apples
    [456] => apples
    [789] => apples
    [987] => bananas
    [654] => bananas
    [321] => bananas
)

Hi actually i did some research on php.net found a solution:

$array3 = array_keys($array1);  
$array4 = array_keys($array2);
$array5 = array_intersect($array3, $array4)
$array6 = array();  

foreach($array5 as $id) {  
    foreach($array1[$id] as $userId) {  
        $array6[$userId] = $array2[$id]  
    }  
}

Probably made more arrays than needed but this works and matches keys of both arrays before assigning values to new array.

Thanks to all that answered and helped!

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