2016-01-30 43 views
0

我有以下阵列如何在php中使用条件对多维数组进行分组?

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 
    ) 
) 

我会怎么做呢?

回答

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); 

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

+0

这很快! –

+1

@是4个元素的快速:)这是一个很好的答案..但考虑使用数据库更大的数据.. – ern

+0

我认为阿德里安在谈论我的答案时间:)但我同意这应该在数据库上完成等级 –

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; 
      } 
     } 
    } 

您的新阵列看起来像这样(店=>价格):

[ 
     1 => 402.50, 
     3 => 235.00 
    ] 
相关问题