Thursday, March 24, 2011

Sorting an array of arrays by the child array's length?

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

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");
From stackoverflow
  • What about just using the length as the array key, then doing a ksort? eg:

    function sort_by_length($parent) { 
      foreach($parent as $child) {
       $sorted[count($child)] = $child;
      }
      return ksort($sorted);
    }
    
  • 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().

  • 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");
    
  • Try the usort function:

    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

0 comments:

Post a Comment