Home > Article > Backend Development > Dictionary sorting problem?
<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>$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