简体   繁体   English

将键从一个数组匹配到另一个数组,并使用其值创建一个新数组?

[英]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) 所以我假设你有2个数组(并且您将第二个数组固定为具有唯一键)

$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: 嗨,实际上我在php.net上做了一些研究,找到了解决方案:

$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! 感谢所有回答和帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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