如何使用php中的条件对多维数组进行分组?

时间:2016-01-30 17:43:56

标签: php arrays multidimensional-array

我有以下数组

   Array
 (
   [0] => Array
        (
        [shop] => 3
        [price] => 332.00
    )

[1] => Array
    (
        [shop] => 1
        [price] => 3335.00
    )

[2] => Array
    (
        [shop] => 3
        [price] => 235.00
    )

[3] => Array
    (
        [shop] => 1
        [price] => 402.50
    )

[4] => Array
    (
        [shop] => 3
        [price] => 332.00
    )



)

我需要使用shop进行分组,并获得阵列中每个商店的最小price

预期结果如下

     Array
 (
   [0] => Array
        (
        [shop] => 3
        [price] => 235.00
    )

[1] => Array
    (
        [shop] => 1
        [price] => 402.50
    )
)

我将如何做?

2 个答案:

答案 0 :(得分:3)

您需要使用其他变量

<?php
$arr = Array
(
    0 => Array
    (
        'shop' => 3,
        'price' => 332.00
    ),
    1 => Array
    (
        'shop' => 3,
        'price' => 232.00
    ),
    2 => Array
    (
        'shop' => 1,
        'price' => 232.00
    ),
    3 => Array
    (
        'shop' => 3,
        'price' => 432.00
    ),
    4 => Array
    (
        'shop' => 1,
        'price' => 132.00
    ),


);
$filtered = array();
foreach($arr as $prices){
    if(FALSE === isset($filtered[$prices['shop']]) || $filtered[$prices['shop']]['price'] > $prices['price']){
        $filtered[$prices['shop']] = $prices;
    }
}

$filtered = array_values($filtered);
print_r($filtered);

这是一个非常快速的例子,你可以如何实现这个

答案 1 :(得分:1)

这很简单。 创建一个新阵列,您将存储商店作为键,价格作为值。你想要做的是遍历每个元素,如果新数组中不存在该键,则添加它及其值。但是,如果密钥已存在,请检查当前值是否较低,如果为true则保存。

    $grouped = [];
    foreach ($arr as $k => $v) {
        foreach ($k as $key => $value) {
            if (isset($grouped[$key])) {
                if ($value < $grouped[$key]) {
                    $grouped[$key] = $value;
                }
            } else {
                $grouped[$key] = $value;
            }
        }
    }

您的新数组将如下所示(store =&gt; price):

    [
        1 => 402.50,
        3 => 235.00
    ]