如何对array_count_values()的结果进行排序?

时间:2017-03-08 06:43:32

标签: php function sorting

Here是我的代码:

<?php
$array = array("world", 1, "hello", 1, "hello", "hello", "how");
$new_array = array_count_values($array);
print_r($new_array);
?>

/* Output:
Array
(
    [world] => 1
    [1] => 2
    [hello] => 3
    [how] => 1
)

现在我想根据新数组的值对结果进行排序。所以这是预期的输出:

/* Expected Output:
Array
(
    [hello] => 3
    [1] => 2
    [world] => 1
    [how] => 1
)

我该怎么做?

注意:相同值的顺序并不重要。

3 个答案:

答案 0 :(得分:5)

您可以使用arsort()按数组对数组进行排序:

<?php
$array = array("world", 1, "hello", 1, "hello", "hello", "how");
$new_array = array_count_values($array);
arsort($new_array, SORT_NUMERIC);
print_r($new_array);
?>

将输出:

Array
(
    [hello] => 3
    [1] => 2
    [world] => 1
    [how] => 1
)

答案 1 :(得分:0)

请尝试下面的代码

<strong>

答案 2 :(得分:0)

使用For fragments: if (id == R.id.nav_things_to_do) { if (id == R.id.nav_things_to_do && viewPager.getCurrentItem() != 0) { Intent main1 = new Intent(getApplicationContext(), MainFragmentsActivity.class); main1.putExtra("position", 0); main1.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); main1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); main1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK); finish(); startActivity(main1); overridePendingTransition(0, 0); drawer.closeDrawer(GravityCompat.START); } else { drawer.closeDrawer(GravityCompat.START); } } if (id == R.id.nav_all_tasks) { if (id == R.id.nav_all_tasks && viewPager.getCurrentItem() != 1) { Intent main2 = new Intent(getApplicationContext(), MainFragmentsActivity.class); main2.putExtra("position", 1); main2.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); main2.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); main2.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK); finish(); startActivity(main2); overridePendingTransition(0, 0); drawer.closeDrawer(GravityCompat.START); } else { drawer.closeDrawer(GravityCompat.START); } } For Activities: if (id == R.id.nav_images) { try { Intent i = new Intent(MainFragmentsActivity.this, SelectFilesActivity.class); i.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); startActivity(i); drawer.closeDrawer(GravityCompat.START); } catch (Exception e) { e.printStackTrace(); } } 按顺序排序,arsort($new_array);表示asc order