0

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.

4
  • 1
    Have you var_dumped the second array? I am sure the result is not what you believe it would be. Commented Jul 1, 2018 at 18:18
  • your second array seems wrong .. is not possible store two different values for the same key Commented Jul 1, 2018 at 18:19
  • Hi @scaisEdge,@frz3993, i updated the question Commented Jul 1, 2018 at 18:21
  • Is the fruits array a collection of all the colors that is in the array or is it irrelevant to the relatedfruits array? Commented Jul 1, 2018 at 18:35

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

You could build the $output array using a nested foreach

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

}

2 Comments

why we can't use array reference here?
Be careful, reference has a different meaning in programming.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.