2016-03-24 24 views
-1

我的陣列:加入數組元素,只顯示最低值

array (size=3) 
    0 => 
    object(stdClass)[20] 
     public 'PkID' => string '488' (length=3) 
     public 'Price' => string '666' (length=3) 
     public 'discount_id' => string '1' (length=1) 
    1 => 
    object(stdClass)[38] 
     public 'PkID' => string '490' (length=3) 
     public 'Price' => string '999' (length=3) 
     public 'discount_id' => string '2' (length=1) 
    2 => 
    object(stdClass)[41] 
     public 'PkID' => string '489' (length=3) 
     public 'Price' => string '111' (length=3) 
     public 'discount_id' => string '1' (length=1) 

問題是如何能予組元件一起共享相同discount_id數目。但是當我分組時,我希望只顯示最低的Price整數。

編輯:我試過

foreach ($array as $value) 
{ 
    $new_array[$value->discount_id] = $value; 
} 

它返回分組陣列像這樣:

array (size=2) 
    1 => 
    object(stdClass)[41] 
     public 'PkID' => string '489' (length=3) 
     public 'Price' => string '111' (length=3) 
     public 'discount_id' => string '1' (length=1) 
    2 => 
    object(stdClass)[38] 
     public 'PkID' => string '490' (length=3) 
     public 'Price' => string '999' (length=3) 
     public 'discount_id' => string '2' (length=1) 

但我不知道如何顯示來自這兩個分組元素最小的代價(在本例以上是最小的,但這只是巧合)

+2

從編寫代碼開始。沒有人會爲你做。 –

+0

請告訴我們您到目前爲止所嘗試過的內容。 (一些PHP代碼) –

+0

您的數據來自數據庫嗎?如果是這樣,你可以在SQL查詢期間對它進行分組。 – Technoh

回答

0
$new_array = array(); 
foreach ($array as $value) { 
    if (array_key_exists($value->discount_id, $new_array)) { // element with given discount_id already exists 
     if ($new_array[$value->discount_id]->Price > $value->Price) { // existing element has higher price - replace it 
      $new_array[$value->discount_id] = $value; 
     } 
    } else { // add new element 
     $new_array[$value->discount_id] = $value; 
    } 
} 

簡化:

$new_array = array(); 
foreach ($array as $value) 
    if (!array_key_exists($value->discount_id, $new_array) || $new_array[$value->discount_id]->Price > $value->Price) // no element or existing element has higher price 
     $new_array[$value->discount_id] = $value; 
+0

謝謝你的先生爲你回答,但我如何檢查'array_key_exists'如果'$ new_array'尚不存在 –

+0

@ShortPort檢查我的更新 –