以降序排列数组值

时间:2018-07-26 20:57:36

标签: php arrays sorting

如何按降序对值进行排序?我试过arsort();但这对我来说不起作用:

$text1 = 'Android SDK, application, familiar with MVP architecture, android studio, angular, angular js';

$skill = array("android sdk"=>"3", "application"=>"1", "angular"=>"2", "android studio"=>"3", "angular js"=>"3");

foreach ($skill as $skills => $weight)            {

if (preg_match_all("~\b$skills\b~i", $text1, $matchWords)) {  

$matchWords = $matchWords[0];

$matchWords = array_unique($matchWords);

}  

$text2 = 'Native Android development';

// Filter $words, keep only the items that are not present in $text2
$missing = array_filter(
    $matchWords,
    function($w) use ($text2) {
        // return TRUE when $w is not in $text
        return preg_match('/\b'.preg_quote($w, '/').'\b/i', $text2) == 0;
});


$weight = array($weight);
$dev = array_combine($missing, $weight);
arsort($dev);

foreach($dev as $x => $x_value) 
     echo "Key: " . $x . " Value: " . $x_value;
     echo "<br>";

}

输出:

键:Android SDK值:3 密钥:应用程序值:1 键:角度值:2 关键:android studio价值:3 密钥:angular js值:3

但是我想得到这个结果:

键:Android SDK值:3 关键:android studio价值:3 密钥:angular js值:3 键:角度值:2 密钥:应用程序值:1

编辑:

我没有找到建议的答案here

3 个答案:

答案 0 :(得分:1)

未正确排序数组的原因是因为您正在尝试对单个元素数组进行排序。如果在代码中放入调试打印,则会在调用$dev时看到arsort仅包含一个元素。您需要在循环中组装$dev,然后对其进行排序。尝试这样的事情:

$text1 = 'Android SDK, application, familiar with MVP architecture, android studio, angular, angular js';
$text2 = 'Native Android development';
$skill = array("android sdk"=>"3", "application"=>"1", "angular"=>"2", "android studio"=>"3", "angular js"=>"3");

foreach ($skill as $skills => $weight) {
    if (preg_match_all("~\b$skills\b~i", $text1, $matchWords)) {  
        $matchWords = $matchWords[0];
        $matchWords = array_unique($matchWords);
    }  
    // Filter $words, keep only the items that are not present in $text2
    $missing = array_filter(
        $matchWords,
        function($w) use ($text2) {
            // return TRUE when $w is not in $text
            return preg_match('/\b'.preg_quote($w, '/').'\b/i', $text2) == 0;
    });

    if (count($missing)) $dev[$missing[0]] = $weight;
}
arsort($dev);

foreach($dev as $x => $x_value) {
    echo "Key: " . $x . " Value: " . $x_value;
    echo "<br>";
}

输出:

Key: Android SDK Value: 3
Key: android studio Value: 3
Key: angular js Value: 3
Key: angular Value: 2
Key: application Value: 1

您的循环代码可以大大简化,但这是另一个问题...

答案 1 :(得分:0)

使用ksort

替换:

arsort($dev);

使用

ksort($dev);

它将按键对数组进行排序

如果需要撤消,请使用array_reverse

ksort($dev);
$dev = array_reverse($dev);

答案 2 :(得分:0)

自定义排序功能

uasort( $dev, function ( $a, $b ) {
    if ( intval( $a ) === intval( $b ) ) {
        return 0;
    }
    return intval( $a ) > intval( $b ) ? -1 : +1;
} );