Home > Mobile >  Combine multi-dimensional arrays based on value from one array and key from another
Combine multi-dimensional arrays based on value from one array and key from another

Time:10-14

I have two multi-dimensional arrays that I'd like to combine by using the value from one of the arrays and the key from the other array. The arrays are as follows:

Array 1:

Array (
  [0] => Array (
    [make] => honda
    [type] => motorcycle
  )
  [1] => Array (
    [make] => toyota
    [type] => truck
  )
  [2] => Array (
    [make] => acura
    [type] => car
  )
  [3] => Array (
    [make] => subaru
    [type] => car
  )
)

Array 2:

Array (
  [honda] => Array (
    [10] => 16000
    [20] => red
    [30] => 2021
  )
  [toyota] => Array (
    [11] => 40000
    [23] => white
    [35] => 2019
  )
  [acura] => Array (
    [12] => 60000
    [25] => black
    [37] => 2020
  )
  [subaru] => Array (
    [181] => 32000
    [27] => blue
    [38] => 2018
  )
)

The resultant array I'd like to produce is the following:

Array (
  [honda] => Array (
    [10] => 16000
    [20] => red
    [30] => 2021
    [type] => motorcycle
  )
  [toyota] => Array (
    [11] => 40000
    [23] => white
    [35] => 2019
    [type] => truck
  )
  [acura] => Array (
    [12] => 60000
    [25] => black
    [37] => 2020
    [type] => car
  )
  [subaru] => Array (
    [181] => 32000
    [27] => blue
    [38] => 2018
    [type] => car
  )
)

Is there a PHP function that I can utilize to accomplish this?

CodePudding user response:

For this example data, you can index the first array by make

$array1 = array_column($array1, 'type', 'make');

Then iterate the second array and append the type from the first array for each make.

foreach ($array2 as $make => $info) {
    $info['type'] = $array1[$make];
    $result[$make] = $info;
}

But using make as a key like seems like it could easily cause problems for you. I don't know where your data comes from, but it doesn't seem unlikely for there to be two items with the same make, which would obviously keep this from working properly. I would suggest finding some other identifier that you could expect to be more unique. VIN would probably be a good choice if you have access to it. If not, you may be able to construct a composite key from multiple similar aspects from each of the data sources

  • Related