如何使用php使用数组引用将两个数组合并为一个?

问题描述:

I have two array, one array has color and another array has fruits, here I want to combine using matching color reference. How to combine by using array reference?

$fruits = ['yellow', 'green', 'orange'];


$relatedFurites = [
['yellow'=>'banana', 'green'=>'avacado'],
['yellow'=>'mango', 'green'=> 'chilli']

];

expected output by using array refernce

$output = [
    'yellow'=>['banana', 'mango'],
    'green'=>['avacado', 'chilli']];

Thanks for all suggestions.

我有两个数组,一个数组有颜色,另一个数组有水果,这里我想用匹配颜色参考组合 。 如何使用数组引用进行组合? p>

  $ fruits = ['yellow','green','orange']; 
 
 
 $ relatedFurites =  [
 ['yellow'=>'banana','green'=>'avacado'],
 ['yellow'=>'mango','green'=>  'chilli'] 
  code>  pre> 
 
 

]; p>

使用数组引用预期输出 p>

  $ output = [
'yellow'=> ['banana','mango'],
'green'=> ['avacado','chilli']]; 
  code  >  pre> 
 
 

感谢您的所有建议。 p> div>

If the $fruits array is related as I asked in comments then you can use array_column and you won't have to iterate every item in the array.

foreach($fruits as $color){
    $output[$color] = array_column($relatedFurites, $color);
}
var_dump($output);

https://3v4l.org/b8tas

You could build the $output array using a nested foreach

foreach ( $relatedFurites as $keyFruites => $valueFruites) {
  foreach( $valueFruites as $key => $value){
    $output[$key][] = $value;
  }

}