2016-01-30 40 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 
    ] 
相關問題