1

I have a new PHP problem. I have 2 arrays, and I want a third array which is a combination of the first 2. The first array, $arr1, is something like this:

Array (
    [0] => name [1] => age
)

The second array, $arr2, is something like this:

Array ( 
    [0] => Array( [0] => Dave [1] => 20 )
    [1] => Array( [0] => Steve [1] => 25 )
    [2] => Array( [0] => Ace [1] => 23 ) 
)

And my idea is to create a new array, called $arr3, which should like this:

Array ( 
    [0] => Array( [name] => Dave [age] => 20 )
    [1] => Array( [name] => Steve [age] => 25 )
    [2] => Array( [name] => Ace [age] => 23 ) 
)

Can anyone tell me how to do this?

3

3 Answers 3

2
$arr3 = array();
foreach ($arr2 as $person) {
    $arr3[] = array_combine($arr1, $person);
}
Sign up to request clarification or add additional context in comments.

Comments

0
foreach($arr2 as $subArray){
      foreach($subArray as $i=>$val){
             $arr3[$arr1[$i]] = $val;
      }
}

Comments

0

Making mapped calls of array_combine() is direct and elegant. Demo

$keys = ['name', 'age'];

$rows = [
    ['Dave', 20],
    ['Steve', 25],
    ['Ace', 23],
];

var_export(
    array_map(
        fn($row) => array_combine($keys, $row),
        $rows
    )
);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.