Reputation: 761
I would like to combine two multidimensional arrays in a way that in the resulting array, array1 values serve as keys for array2.
These are two example arrays:
$array1 = array(
array('data1'),
array('data2'),
array('data3')
);
$array2 = array(
array('5','12','4'),
array('8','2','17'),
array('20','15','3')
);
The resulting array should look like this:
$array = array(
'data1' => array('5','12','4'),
'data2' => array('8','2','17'),
'data3' => array('20','15','3')
);
How could I achieve this? Thanks!
Upvotes: 0
Views: 1941
Reputation: 47874
This can be succinctly accomplished using just two native php functions.
The only step before calling array_combine()
is to reduce the depth of your first array. To extract the first value from each subarray, just call array_column()
and specify that you want all of the 0
-keyed values.
Code: (Demo)
$array1 = [['data1'], ['data2'], ['data3']];
$array2 = [['5', '12', '4'], ['8', '2', '17'], ['20', '15', '3']];
var_export(
array_combine(array_column($array1, 0), $array2)
);
Output:
array (
'data1' =>
array (
0 => '5',
1 => '12',
2 => '4',
),
'data2' =>
array (
0 => '8',
1 => '2',
2 => '17',
),
'data3' =>
array (
0 => '20',
1 => '15',
2 => '3',
),
)
Upvotes: 0
Reputation: 16122
Use array_map(), which lets you use user defined function.
<?php
$array1 = array(
array('data1'),
array('data2'),
array('data3')
);
$array2 = array(
array('5', '12', '4'),
array('8', '2', '17'),
array('20', '15', '3')
);
function mapArray($array1, $array2) {
return [$array1[0] => $array2];
}
$new_arr = array_map("mapArray", $array1, $array2);
Output
Upvotes: 1
Reputation: 28529
You can use array_combine to combine keys and values to an new array. You can check the live demo here.
array_combine(array_map(function($v){return $v[0];},$array1), $array2);
Upvotes: 1
Reputation: 3040
$array1 = array(
array('data1'),
array('data2'),
array('data3')
);
$array2 = array(
array('5','12','4'),
array('8','2','17'),
array('20','15','3')
);
$main_array=array(count($array1));
foreach($array as $array_item){
$array_item=array(count($array2));
for($i=1;$i<count($array2);$i++){
array.push($array_item,$array2[$i]);
}
array.push($main_array,$array_item);
}
echo "<br>";
print_r($main_array);
echo "</br>";
Upvotes: -1
Reputation: 2000
You can do something like this
$array = [];
$count = count($array1);
for($index = 0; $index < $count; $index++)
{
$array[$array1[$index][0]] = $array2[$index];
}
This should do what you are trying to achieve
Upvotes: 2