来自多维数组的填充数据

时间:2015-10-10 13:41:21

标签: php arrays

从数组中查找数据。

Array
(

    [0] => Array
        (
            [id] => 2000
            [rating] => 5
            [length] => 89
        )

    [1] => Array
        (
            [id] => 2000
            [rating] => 5
            [length] => 80   
   )

    [2] => Array
        (
            [id] => 2000
            [rating] => 1
            [length] => 105 
       )
   [3] => Array
        (
            [id] => 2000
            [rating] => 5
            [length] => 90 
    )

   [4] => Array
        (
            [id] => 2001
            [rating] => 4
            [length] => 55 
    )
  [5] => Array
        (
            [id] => 2001
            [rating] => 3
            [length] => 55 
    )
)

如果id相同,则为必需条件:

  1. 获取具有最高评级的记录。
  2. 如果数组中的评分相同,则根据长度(最大长度)得到结果
  3. 必需输出:

    array(
       [3] => Array
        (
            [0] => 2000
            [1] => 5
            [2] => 90 
       )
      [4] => Array
       (
            [id] => 2001
            [rating] => 4
            [length] => 55 
     )
    )
    

2 个答案:

答案 0 :(得分:1)

您可以像{/ p>一样使用usort和简单foreach循环

usort($arr,function($a,$b){
    $c = $b['rating'] - $a['rating'];
    $c .= $b['length'] - $a['length'];
    return $c;
});
$result = [];
foreach($arr as $key => $value){
    if(!isset($result[$value['id']])){
        $result[$value['id']] = $value;
    }
}
print_r(array_values($result));

答案 1 :(得分:0)

(我认为你应该重新制定你的问题,它非常混乱......)

如果你需要排序,也许你可以使用foreach()。

//$max = 0;
foreach( $arrayWithSameIds as $key => $element){

  if($element['rating'] > $max){ 
    //$max = $element;
  }else if($element['rating'] == $max){
    //compare $max['length'] and $element['length']
  }else{

  }

}

我不满足于你所寻找的......