PHP-如何根据变量字符的外观对数组进行排序

PHP-如何根据变量字符的外观对数组进行排序,php,arrays,sorting,Php,Arrays,Sorting,我有一个数组 $array = array("no_spaces","one space","two 2 spaces"); 我想按特定字符出现的频率对数组进行排序/排序。在本例中为“” 作为回报,我将得到以下数组 [0]=> string(12) "two 2 spaces" [1]=> string(9) "one space" [2]=> string(10) "no_spaces" 我一直在浏览php.net手册,没有

我有一个数组

$array = array("no_spaces","one space","two 2 spaces");
我想按特定字符出现的频率对数组进行排序/排序。在本例中为“”

作为回报,我将得到以下数组

    [0]=>
    string(12) "two 2 spaces"
    [1]=>
    string(9) "one space"
    [2]=>
    string(10) "no_spaces"

我一直在浏览php.net手册,没有找到任何可以做到这一点的命令。有什么想法吗?

这应该适合你:

只需与一起使用即可对数组进行排序,例如

usort($array, function($a, $b){
    return substr_count($b, " ") - substr_count($a, " ");
});

usort
与搜索字符(或图案)的方法结合使用

$array=array(“无空格”、“一空格”、“无空格”、“两个2空格”、“两个1空格”、“两个3空格”);
usort($array,“charSort”);
回声';
打印(数组);
回声';
函数charSort($a,$b){
预匹配全部('/',$a,$aa);
预匹配全部('/',$b,$bb);
如果(计数($aa[0])==计数($bb[0]))
返回0;
返回(计数($aa[0])<计数($bb[0])?-1:1;
}
$array = array("no_spaces","one space","no_space","two 2 spaces", "two 1spaces", "two 3 3 spaces");
usort( $array, "charSort" );

echo '<pre>';
print_r( $array );
echo '</pre>';

function charSort($a, $b) {
    preg_match_all( '/ /', $a, $aa );
    preg_match_all( '/ /', $b, $bb );
    if( count( $aa[0] ) == count( $bb[0] ) )
        return 0;
    return (count( $aa[0] ) < count( $bb[0] )) ? -1 : 1;
}