根据子数组的长度对数组排序?

时间:2020-12-27 21:42:55

What's the best way in PHP to sort an array of arrays based on array length?

在PHP中,根据数组长度对数组排序的最佳方法是什么?

e.g.

如。

$parent[0] = array(0, 0, 0);
$parent[2] = array("foo", "bar", "b", "a", "z");
$parent[1] = array(4, 2);

$sorted = sort_by_length($parent)

$sorted[0] = array(4, 2);
$sorted[1] = array(0, 0, 0);
$sorted[2] = array("foo", "bar", "b", "a", "z");

4 个解决方案

#1


3  

This will work:

这将工作:

function sort_by_length($arrays) {
    $lengths = array_map('count', $arrays);
    asort($lengths);
    $return = array();
    foreach(array_keys($lengths) as $k)
        $return[$k] = $arrays[$k];
    return $return;
}

Note that this function will preserve the numerical keys. If you want to reset the keys, wrap it in a call to array_values().

注意,这个函数将保留数字键。如果希望重置键,请将其封装到array_values()调用中。

#2


2  

I'm upvoting Peter's but here's another way, I think:

我支持彼得,但我想,还有另一种方式

function cmp($a1, $a2) {
    if (count($a1) == count($a2)) {
        return 0;
    }
    return (count($a1) < count($a2)) ? -1 : 1;
}

usort($array, "cmp");

#3


0  

What about just using the length as the array key, then doing a ksort? eg:

用长度作为数组键,然后做ksort怎么样?例如:

function sort_by_length($parent) { 
  foreach($parent as $child) {
   $sorted[count($child)] = $child;
  }
  return ksort($sorted);
}

#4


0  

Try the usort function:

试试usort函数:

function sortByLength( $arr1, $arr2 )
{
    $c1 = count($arr1);
    $c2 = count($arr2);

    return $c1 < $c2 ? -1 : $c1 == $c2 ? 0 : 1;
}

usort($initial_array,'sortByLength');

edited to respect parameters-by-reference; it's the same answer as @david, anyway

编辑尊重parameters-by-reference;这和@david的答案是一样的

#1


3  

This will work:

这将工作:

function sort_by_length($arrays) {
    $lengths = array_map('count', $arrays);
    asort($lengths);
    $return = array();
    foreach(array_keys($lengths) as $k)
        $return[$k] = $arrays[$k];
    return $return;
}

Note that this function will preserve the numerical keys. If you want to reset the keys, wrap it in a call to array_values().

注意,这个函数将保留数字键。如果希望重置键,请将其封装到array_values()调用中。

#2


2  

I'm upvoting Peter's but here's another way, I think:

我支持彼得,但我想,还有另一种方式

function cmp($a1, $a2) {
    if (count($a1) == count($a2)) {
        return 0;
    }
    return (count($a1) < count($a2)) ? -1 : 1;
}

usort($array, "cmp");

#3


0  

What about just using the length as the array key, then doing a ksort? eg:

用长度作为数组键,然后做ksort怎么样?例如:

function sort_by_length($parent) { 
  foreach($parent as $child) {
   $sorted[count($child)] = $child;
  }
  return ksort($sorted);
}

#4


0  

Try the usort function:

试试usort函数:

function sortByLength( $arr1, $arr2 )
{
    $c1 = count($arr1);
    $c2 = count($arr2);

    return $c1 < $c2 ? -1 : $c1 == $c2 ? 0 : 1;
}

usort($initial_array,'sortByLength');

edited to respect parameters-by-reference; it's the same answer as @david, anyway

编辑尊重parameters-by-reference;这和@david的答案是一样的