Home >Backend Development >PHP Tutorial >Dictionary sorting problem?

Dictionary sorting problem?

WBOY
WBOYOriginal
2016-12-05 13:44:15966browse

<code>$a=array(2,1,4,7,1,4,1,9)
</code>

I want to get key/value, where key is the value and value is the number of times the value appears, as shown below:

<code>$b={2:1,1:3,4:2,7:1,9:1}
</code>

There are many elements in $a. How to solve this problem with the fewest loops?

Reply content:

<code>$a=array(2,1,4,7,1,4,1,9)
</code>

I want to get key/value, where key is the value and value is the number of times the value appears, as shown below:

<code>$b={2:1,1:3,4:2,7:1,9:1}
</code>

There are many elements in $a. How to solve this problem with the fewest loops?

<code class="php">// 直接用函数
>>> array_count_values($a)
=> [
     2 => 1,
     1 => 3,
     4 => 2,
     7 => 1,
     9 => 1,
   ]
</code>

<code>$b = [];
foreach ($a as $i) {
   $b[$i] =  isset($b[$i]) ? $b[$i] + 1 : 0;
}</code>

Loop once

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn