php,保持多维数组的最高价值

时间:2017-05-30 18:24:21

标签: php arrays multidimensional-array

我有一个多维数组,如下所示:

Array
(
    [0] => Array
        (
            [name] => name1
            [sha1] => sha1
            [size] => 693989968
        )

    [1] => Array
        (
            [name] => name1
            [sha1] => sha2
            [size] => 757204238
        )

    [2] => Array
        (
            [name] => name2
            [sha1] => sha3
            [size] => 1068277922
        )

    [3] => Array
        (
            [name] => name3
            [sha1] => sha4
            [size] => 996843467
        )

想要的函数的返回应该是sha2,sha3,sha4;如果名称不止一次,则应保留较高的大小。

我现在尝试了几个小时,使用asort,分成多个数组(名称,sha和大小),但直到现在都没有。

1 个答案:

答案 0 :(得分:0)

$output_array=array();
$a = array(
 array(
   "name" => "name1",
   "sha1" => "sha1",
   "size" => 693989968
 ),
 array(
   "name" => "name1",
   "sha1" => "sha2",
   "size" => 757204238
 ),
 array(
   "name" => "name2",
   "sha1" => "sha3",
   "size" => 1068277922
 ),
 array(
   "name" => "name3",
   "sha1" => "sha4",
   "size" => 996843467
 )
);
foreach($a as $item){
  //item to check
  $item_tc = @$output_array[$item['name']]; //names with empty string will be discarded
  //by using @ to suppress errors.
  if($item_tc){
      print($item['size'].'n');
      print($item_tc['size']);
      if($item['size'] > $item_tc['size']){
           $output_array[$item['name']] = $item;
              //print_r($item);

       }
    }else{
      $output_array[$item['name']] = $item; 
    }
}
print_r($output_array);

输出结果为:

Array (
  [name1] => Array ( 
    [name] => name1 
    [sha1] => sha2 
    [size] => 757204238 
   ) 
   [name2] => Array (
    [name] => name2 
    [sha1] => sha3 
    [size] => 1068277922 
  ) 
  [name3] => Array ( 
    [name] => name3 
    [sha1] => sha4 
    [size] => 996843467 
  ) 
)