2017-01-03 39 views
1

我有一個PHP數組:PHP濾波器陣列只有一個屬性值

$myarray = array(
    array(
    'id' = '1', 
    'number' = '2' 
), 
    array(
    'id' = '1', 
    'number' = '3' 
), 
    array(
    'id' = '2', 
    'number' = '5' 
), 
    array(
    'id' = '2', 
    'number' = '2' 
), 
); 

我需要過濾數組並獲得唯一一個「身份證」與最大數值。

例expecty輸出:

$myarray = array(
array(
    'id' = '1', 
    'number' = '3' 
), 
    array(
    'id' = '2', 
    'number' = '5' 
) 
); 

如何過濾呢?

我試圖循環它,但它沒有工作。

$array = array(); 
for($i = 0; $i < count($myarray);$i++) { 
//If not contains in $array , push to $array 
       $array []['id'] = $myarray[$x]['id']; 
       $array []['number'] = $myarray[$x]['number']; 

      } 
+0

告訴我們你嘗試過什麼。 – emaillenin

+0

現在就編輯.. –

+0

你說你「期待只有一個'id'最大數值」,但你的例子輸出顯示了兩個項目。我不清楚。 – karliwson

回答

0

下面是一個簡單的類來做到這一點:

class FilterMax 
    { 
     private $temp = []; 
     private $array = []; 

     public function __construct($array) 
     { 
      if (!is_array($array)) { 
       throw new InvalidArgumentException('Array should be an array'); 
      } 
      $this->array = $array; 
     } 

     public function getFilteredResults($searchKey = 'id', $searchValue = 'number') 
     { 
      foreach ($this->array as $index => $item) { 
       if (!isset($item[ $searchKey ]) || !isset($item[ $searchValue ])) { 
        throw new Exception('Key or value does not exists in array'); 
       } 
       $itemKey = $item[ $searchKey ]; 
       if (!isset($this->temp[ $itemKey ])) { 
        $this->temp[ $itemKey ] = $index; 
       } 
       else { 
        $itemValue = $item[ $searchValue ]; 
        $tempIndex = $this->temp[ $itemKey ]; 
        $tempValue = $this->array[ $tempIndex ][ $searchValue ]; 
        if ($itemValue > $tempValue) { 
         unset($this->array[ $tempIndex ]); 
        } 
        else { 
         unset($this->array[ $index ]); 
        } 
       } 
      } 

      return $this->array; 
     } 
    } 

把你的陣列

$myarray = [ 
       [ 
        'id'  => '1', 
        'number' => '2', 
       ], 
       [ 
        'id'  => '1', 
        'number' => '3', 
       ], 
       [ 
        'id'  => '2', 
        'number' => '5', 
       ], 
       [ 
        'id'  => '2', 
        'number' => '2', 
       ], 
      ]; 

而且使用這樣的:

  $filterMax = new FilterMax($myarray); 
      $result = $filterMax->getFilteredResults('id', 'number'); 
0

創建關聯數組的鍵是id,和值包含從原始數組最大number

$maxes = array(); 
foreach ($myarray as $el) { 
    $id = $el['id']; 
    $num = $el['number']; 
    if (!isset($maxes[$id])) { 
     $maxes[$id] = array('id' => $id, 'number' => $num); 
    } elseif ($num > $maxes[$id]['number']) { 
     $maxes[$id]['number'] = $number; 
    } 
}