Combine arrays to form multidimensional array in php
Solution 1
If you have control over creating the arrays, you should create them like:
$a = array ('1421' ,'2241');
$b = array ('teststring1', 'teststring3', 'teststring5');
$c = array ('teststring2', 'teststring4', 'teststring6');
$e = array_combine($a, array($b,$c) );
If not, you have to loop over them:
$result = array();
$values = array($b, $c, $d);
foreach($a as $index => $key) {
$t = array();
foreach($values as $value) {
$t[] = $value[$index];
}
$result[$key] = $t;
}
Solution 2
Here is a one-liner in a functional coding style. Calling array_map()
with a null
function parameter followed by the "values" arrays will generate the desired subarray structures. array_combine()
does the key=>value associations.
Code (Demo)
var_export(array_combine($a, array_map(null, $b, $c, $d)));
Output:
array (
1421 =>
array (
0 => 'teststring1',
1 => 'teststring3',
2 => 'teststring5',
),
2241 =>
array (
0 => 'teststring2',
1 => 'teststring4',
2 => 'teststring6',
),
)
Super clean, right? I know. It's a useful little trick when you don't have control of the initial array generation step.
Tek
Updated on June 16, 2022Comments
-
Tek almost 2 years
I know there's a ton of answers but I can't seem to get it right. I have the following arrays and what I've tried:
$a = array ( 0 => '1421' , 1 => '2241' ); $b = array ( 0 => 'teststring1' , 1 => 'teststring2' ); $c = array ( 0 => 'teststring3' , 1 => 'teststring4' ); $d = array ( 0 => 'teststring5' , 1 => 'teststring6' ); $e = array_combine($a, array($b,$c,$d) );
But with this I get the error
array_combine() [function.array-combine]: Both parameters should have an equal number of elements
.I know it's because the
$a
's array values aren't keys. That's why I'm coming here to see if I could get some help with an answer that can help me make it look something like this:array(2) { [1421]=>array( [0] => teststring1 [1] => teststring3 [2] => teststring5 ) [2241]=>array( [0] => teststring2 [1] => teststring4 [2] => teststring6 ) }
-
Tek over 13 yearsI had JUST edited and found out a loop similar to this. I have erased my edit and I'll just mark this as solved. I have used your loop since I like it more than the one I wrote. Thanks! PS. Thanks for adding the bit about not having control over them, because I didn't since I had used
array_fill.