2016-03-24 4 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番号を共有して一緒にI族元素ことができます。しかし私がグループ化するとき、私は最低のPrice整数だけが表示されることを望む。

EDIT:

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) 

しかし、私は一例でこれら二つのグループ化された要素(から最小の価格を表示する方法を知りません。私はそうのようにグループ化された配列を返す

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

を試してみましたこれは最小ですが、これは偶然にすぎません)

+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

ありがとうございました。あなたにはお答えいただきありがとうございます。しかし、 '$ new_array'がまだ存在しない場合、' array_key_exists'をどうやって確認するのですか? –

+0

@ShortPortは私のアップデートをチェックします –

関連する問題