Bart Bart - 22 days ago 6
PHP Question

Create multidimensional array from newly combined arrays

I have a couple of arrays that I want to combine into new arrays but each new array needs to have one value from each value. Just creating a multidimensional array is not enough. So any help would be great.

I have this array

Array (
[0] => Array (
[0] => Supplier 1
[1] => Supplier 1
[2] => Supplier 2
)

[1] => Array (
[0] => Product 1
[1] => Product 2
[2] => Product 3
)

[2] => Array (
[0] => 123456
[1] => 654321
[2] => 111111
)

[3] => Array (
[0] => 7
[1] => 40
[2] => 5
)
)


But I need it to be like this

Array (
[0] => Array (
[supplier] => Supplier 1
[descr] => Product 1
[partid] => 123456
[quantity] => 7
)

[1] => Array (
[supplier] => Supplier 1
[descr] => Product 2
[partid] => 654321
[quantity] => 40
)

[2] => Array (
[supplier] => Supplier 2
[descr] => Product 3
[partid] => 111111
[quantity] => 5
)
)

Answer

You can use the PHP method array_map[1] to perform this (assuming that your original multi-dimensional array is in $arr):

$res = array_map(
    function ($lev, $oms, $num, $aan) {
        return [
            'leverancier' => $lev,
            'artikel_omschrijving' => $oms,
            'artikelnummer' => $num,
            'artikel_aantal' => $aan
        ];
    },
    $arr[3],
    $arr[1],
    $arr[0],
    $arr[2]);

What it does is loop through all n arrays passed at the end of the function call, and passes the entry at the same position in each array to the callback function.

[1] http://php.net/manual/en/function.array-map.php