Thursday, 30 August 2018

Combine two multidimensional arrays and define one as a key

I have these two arrays, which I need to combine

Array (
    [0] => Column 1
    [1] => Column 2
    [2] => Column 3
)
Array (
    [0] => Array (
            [0] => 111
            [1] => 222
            [2] => 333
        )
    [1] => Array (
            [0] => 444
            [1] => 555
            [2] => 666
        )
)

into this
Array (
    [0] => Array (
            [Column 1] => 111
            [Column 2] => 222
            [Column 3] => 333
        )
    [1] => Array (
            [Column 1] => 444
            [Column 2] => 555
            [Column 3] => 666
        )
)

This is what I have and it works, but I am sure it can be done in a simpler way:
$values = array( array( 1,2,3), array( 4,5,6) );
$fields = array( 'Column 1','Column 2','Column 3');
$i = 0;
$j = 0;
$l = 0;
$rows = array();
$columns = array();

foreach($values as $val) {
    $rows[] = $val;

    foreach ($fields as &$field) {
        $columns[$j][$i] = $field;
        $i++;
    }
    $i = 0;
    $j++;
}

foreach($columns as $c){
    $result[] = array_combine($c,$rows[$l]);
    $l++;
}

What I would like is to clean it up if possible. I do have my struggle with arrays sometimes and this one really messed with my head. :-)

Iterate over the array of arrays and pass each array to array_combine [docs], together with the keys:
$result = array();

foreach($values as $key => $value) {
    $result[$key] = array_combine($fields, $value);
}

0 comments:

Post a Comment