Jhonny Jr. Jhonny Jr. - 5 months ago 16
PHP Question

Multiplying 2 array multidimensional and remove key

I have an multidimensional array which contain some numbers, and i want to multiplying value of array which contain key 0 with each other key inside one area array and erase key 0.

Array

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

[1] => Array
(
[0] => 2
[1] => 7
[2] => 4
[3] => 2
[4] => 8
)

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


Here's the result i want

Array
(
[0] => Array
(
[0] => 15
[1] => 15
[2] => 18
[3] => 21
)

[1] => Array
(
[0] => 14
[1] => 8
[2] => 4
[3] => 16
)

[2] => Array
(
[0] => 8
[1] => 12
[2] => 8
[3] => 20
)
)


I was already combine it using foreach and for, but it still not working for me, any idea how to do this?

Answer

The solution using array_map and array_slice functions:

// $arr is your initial array
foreach ($arr as &$v) {
    $multiplier = $v[0];
    $v = array_map(function($val) use($multiplier){
        return  $multiplier * $val;        
    }, array_slice($v, 1));
}

print_r($arr);

The output:

Array
(
    [0] => Array
        (
            [0] => 15
            [1] => 15
            [2] => 18
            [3] => 21
        )

    [1] => Array
        (
            [0] => 14
            [1] => 8
            [2] => 4
            [3] => 16
        )

    [2] => Array
        (
            [0] => 8
            [1] => 12
            [2] => 8
            [3] => 20
        )
)
Comments