Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine arrays to form multidimensional array in php

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
               )


}
like image 647
Tek Avatar asked Oct 13 '22 20:10

Tek


2 Answers

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;
}

DEMO

like image 177
Felix Kling Avatar answered Oct 18 '22 01:10

Felix Kling


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.

like image 39
mickmackusa Avatar answered Oct 18 '22 03:10

mickmackusa