连接数组元素,仅显示最低值

时间:2016-03-24 13:54:56

标签: php arrays

我的阵列:

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)

但我不知道如何从这两个分组元素中显示最小的价格(在上面的例子中它是最小的,但这只是巧合)

1 个答案:

答案 0 :(得分: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;
相关问题