Home > Mobile >  How to merge two arrays when a key of one of them and a value of the other array is match
How to merge two arrays when a key of one of them and a value of the other array is match

Time:05-26

I am looking for a way to merge two arrays and create two dimension array.

dayArray

(
    [1] => tue
    [2] => wed
    [4] => fri
    [5] => sat

I would like to assign the values below.

fruitArray

array (
  'tue' => 'banana',
  'fri' => 'apple',
  'sat' => 'orange',
)  

two-dimensional array expected result

  $array = [
   1 =>['tue','banana'],
   2 =>['wed'],
   4 =>['fri','apple'],
     5 =>['sat','orange']

I tried to make it

{
    foreach ($dayArray as $key => $value)
    {
        if($fruitArray[$value]){
            $dayArray[$key] = array($key,$value,$fruitArray[$value]);
        }
    }
}

ErrorException: Trying to access array offset on value of type null in f

CodePudding user response:

Use this

check day key available in fruitArray using isset method

$dayArray = array('tue','wed','fri','sat');
// print_r($array);
$fruitArray = array (
  'tue' => 'banana',
  'fri' => 'apple',
  'sat' => 'orange',
);
$newTwoDimensionalArray = [];
foreach($dayArray as $day){
  if(isset($fruitArray[$day])){
    $newTwoDimensionalArray[] = [$day,$fruitArray[$day]];
  } else {
    $newTwoDimensionalArray[] = [$day,''];
  }
}

CodePudding user response:

looks like you forgot to add isset() for checking whether key is exist or not:

if(isset($fruitArray[$value])){
   $dayArray[$key] = [$value,$fruitArray[$value]);
}
else {
   $dayArray[$key] = [$value];
}

CodePudding user response:

$dayArr = array(1 => 'tue', 2 => 'wed', 4 => 'fri',5 => 'sat');
$fruitArr = array (
   'tue' => 'banana',
   'fri' => 'apple',
   'sat' => 'orange',
);
$result = array_map(function ($val) use ($fruitArr) {
   return array_key_exists($val, $fruitArr) ? [$val, $fruitArr[$val]] : [$val];
}, $dayArr);

  •  Tags:  
  • php
  • Related