对值计数的多维数组排序

时间:2015-11-16 12:26:25

标签: php arrays

我在下面有数组:

Array
(
[Lackberg, Camilla] => Array
    (
        [0] => 0007253958
    )

[Connolly, John] => Array
    (
        [0] => 1501122665
        [1] => 1501122673
    )

[Higgins, Jack] => Array
    (
        [0] => 0007452241
    )

[Ryan, Hank Phillippi] => Array
    (
        [0] => 0765384779
        [1] => 0765384787
        [2] => 0765384744
        [3] => 0765384752
    )

}

我需要输出如下

Array
(
[Ryan, Hank Phillippi] => Array
    (
        [0] => 0765384779
        [1] => 0765384787
        [2] => 0765384744
        [3] => 0765384752
    )
[Connolly, John] => Array
    (
        [0] => 1501122665
        [1] => 1501122673
    )
[Lackberg, Camilla] => Array
    (
        [0] => 0007253958
    )


[Higgins, Jack] => Array
    (
        [0] => 0007452241
    )
 }

1 个答案:

答案 0 :(得分:0)

  

使用应保留密钥的uasort功能

$array = array(
          "Lackberg, Camilla"=> Array ('0007253958'),
          "Connolly, John" => Array('1501122665','1501122673'),
          "Higgins, Jack" => Array('0007452241'),
          "Ryan, Hank Phillippi" => Array('0765384779','0765384787','0765384744','0765384752')
        );

    function cmp($a, $b){
        return (count($b) - count($a));
    }

    uasort($array, 'cmp');

    var_dump($array);

<强>输出:

array (size=4)
      'Ryan, Hank Phillippi' => 
        array (size=4)
          0 => string '0765384779' (length=10)
          1 => string '0765384787' (length=10)
          2 => string '0765384744' (length=10)
          3 => string '0765384752' (length=10)
      'Connolly, John' => 
        array (size=2)
          0 => string '1501122665' (length=10)
          1 => string '1501122673' (length=10)
      'Lackberg, Camilla' => 
        array (size=1)
          0 => string '0007253958' (length=10)
      'Higgins, Jack' => 
        array (size=1)
          0 => string '0007452241' (length=10)

  

首先计算数组值并使用相同的键存储在$temp数组中,然后使用asort()

对值进行排序      然后你得到了订单!

$array = array(
  "Lackberg, Camilla"=> Array ('0007253958'),
  "Connolly, John" => Array('1501122665','1501122673'),
  "Higgins, Jack" => Array('0007452241'),
  "Ryan, Hank Phillippi" => Array('0765384779','0765384787','0765384744','0765384752')
);
foreach ($array as $key => $value) {
  $temp[$key] = count($value);
}
arsort($temp);
foreach ($temp as $key => $value){
$temps[$key] =  $array[$key];
}
var_dump($temps);

<强>输出:

array (size=4)
  'Ryan, Hank Phillippi' => 
    array (size=4)
      0 => string '0765384779' (length=10)
      1 => string '0765384787' (length=10)
      2 => string '0765384744' (length=10)
      3 => string '0765384752' (length=10)
  'Connolly, John' => 
    array (size=2)
      0 => string '1501122665' (length=10)
      1 => string '1501122673' (length=10)
  'Lackberg, Camilla' => 
    array (size=1)
      0 => string '0007253958' (length=10)
  'Higgins, Jack' => 
    array (size=1)
      0 => string '0007452241' (length=10)

我希望这有助于实现!! 快乐编码!!