2012-11-27 64 views
-1

我如何通過houseid對這個數組進行分組?如何在PHP中對數組進行分組?

Array 
(
    [0] => stdClass Object 
     (
      [id] => 1111 
      [houseid] => 58 
      [price] => 2995 
     ) 

    [1] => stdClass Object 
     (
      [id] => 1112 
      [houseid] => 58 
      [price] => 4050 
     ) 

    [2] => stdClass Object 
     (
      [id] => 1114 
      [houseid] => 60 
      [price] => 1695 
     ) 

    [3] => stdClass Object 
     (
      [id] => 1115 
      [houseid] => 60 
      [price] => 2250 
     ) 

    [4] => stdClass Object 
     (
      [id] => 1116 
      [houseid] => 60 
      [price] => 2295 
     ) 
) 

我需要計算總價格爲houseid和做一些數學/條件,如果組數組...

我可以格式化這個數組類似

它會很容易
Array 
(
    [58] => stdClass Object(
     [0] => stdClass Object 
     (
      [id] => 1111 
      [price] => 2995 
     ) 
     [1] => stdClass Object 
     (
      [id] => 1112 
      [houseid] => 58 
      [price] => 4050 
     ) 
    ) 
    [60] => stdClass Object(
     [0] => stdClass Object(
      [id] => 1114 
      [price] => 1695 
     ) 
     [1] => stdClass Object 
     (
      [id] => 1115 
      [price] => 2250 
     ) 
     [2] => stdClass Object 
     (
      [id] => 1116 
      [price] => 2295 
     ) 
) 

或者任何人都可以建議我,如何循環原始數組來計算一個房子的總價格?

+0

向我們展示[你已經試過(http://www.whathaveyoutried.com)。這方面有很多類似的問答。 – Kermit

+0

我需要得到一些日期之間的houseids,並從sql語句中得到這個數組...我需要將它重新格式化爲需要 –

+1

,它們有很多數組函數,他們至少應該在提問之前檢查它們顯示沒有努力 –

回答

3

您可以使用array_reduce

$data = array_reduce($data, function ($a, $b) { 
    $id = $b->houseid; 
    unset($b->houseid); 
    $a[$id][] = $b; 
    return $a; 
}); 

var_dump($data); 

輸出

array (size=2) 
    58 => 
    array (size=2) 
     0 => 
     object(stdClass)[1] 
      public 'id' => int 1111 
      public 'price' => int 2995 
     1 => 
     object(stdClass)[2] 
      public 'id' => int 1112 
      public 'price' => int 4050 
    60 => 
    array (size=3) 
     0 => 
     object(stdClass)[3] 
      public 'id' => int 1114 
      public 'price' => int 1695 
     1 => 
     object(stdClass)[4] 
      public 'id' => int 1115 
      public 'price' => int 2250 
     2 => 
     object(stdClass)[5] 
      public 'id' => int 1116 
      public 'price' => int 2295 

Full live Demo

+1

OMG,我從來不知道有關array_reduce,非常感謝Baba ...... –

相關問題