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

Dictionary sorting problem?

WBOY
Release: 2023-03-03 09:08:01
Original
1002 people have browsed it

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

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>
Copy after login
Copy after login

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>
Copy after login
Copy after login

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>
Copy after login
Copy after login

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>
Copy after login

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

Loop once

Related labels:
php
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template