PHP乘以两个多维数组

时间:2018-02-06 10:36:17

标签: php arrays codeigniter

我有两个多维数组

数组1

Array(
    "2" => Array
        (
            "quantity" => 2,
            "id" => 2
        ),

    "1" => Array
        (
            "quantity" => 1,
            "id" => 1
        ),

    "3" => Array
        (
            "quantity" => 1,
            "id" => 3
        ));

数组2

Array(
    "0" => Array
        (
            "id" => 1,
            "name" => "2Bed Room",
            "room" => 6,
            "bed" => 12,
            "price" => 2800,
            "available_room" => 6,
            "available_bed" => 12,
            "extra_bed" => 500,
        ),

    "1" => Array
        (
            "id" => 2,
            "name" => "3Bed Room",
            "room" => 12,
            "bed" => 36,
            "price" => 3800,
            "available_room" => 12,
            "available_bed" => 36,
            "extra_bed" => 500,
        ),

    "2" => Array
        (
            "id" => 3,
            "name" => "Dormitory",
            "room" => 8,
            "bed" => 16,
            "price" => 750,
            "available_room" => 8,
            "available_bed" => 16,
            "extra_bed" => 500,
        ));

我想基于id。

乘以值

例如Array 1包含[id] => 2

Array 2具有相同的ID [id] => 2

如果要求符合要求,那么多个Array 1数量到Array 2价格 并以数组格式返回。

感谢您的重播

1 个答案:

答案 0 :(得分:1)

您可以使用array_column来隔离您需要的部分,然后将其预先加倍并相乘。

$arr1 = Array(
    "2" => Array
        (
            "quantity" => 2,
            "id" => 2
        ),

    "1" => Array
        (
            "quantity" => 1,
            "id" => 1
        ),

    "3" => Array
        (
            "quantity" => 1,
            "id" => 3
        ));

$arr2 = Array(
    "0" => Array
        (
            "id" => 1,
            "name" => "2Bed Room",
            "room" => 6,
            "bed" => 12,
            "price" => 2800,
            "available_room" => 6,
            "available_bed" => 12,
            "extra_bed" => 500,
        ),

    "1" => Array
        (
            "id" => 2,
            "name" => "3Bed Room",
            "room" => 12,
            "bed" => 36,
            "price" => 3800,
            "available_room" => 12,
            "available_bed" => 36,
            "extra_bed" => 500,
        ),

    "2" => Array
        (
            "id" => 3,
            "name" => "Dormitory",
            "room" => 8,
            "bed" => 16,
            "price" => 750,
            "available_room" => 8,
            "available_bed" => 16,
            "extra_bed" => 500,
        ));

$arrone = array_column($arr1, "quantity", "id"); // arrone is now  associatvie array with quantity as value
$arrtwo = array_column($arr2, "price", "id"); // arrtwo is now associative array with price as value

foreach($arrone as $key => $val){
    $total[$key] = $arrtwo[$key] * $val; // multiply them and add them to total array
}

var_dump($total);

https://3v4l.org/NLpt9

在现实世界中,您可能需要确保$ arrtwo中存在$ key。但是,如果数据输入是安全/可靠的,则此代码将起作用。