2017-01-03 11 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' 
), 
); 

私はこの配列をフィルタリングし、最大数の値を持つ唯一の「ID」を取得する必要があります。

例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

あなたは "最大数の値で1つの 'id'しか期待していませんが、あなたの出力例には2つの項目があります。私には明らかではない。 – 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; 
    } 
}