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

Dictionary sorting problem?

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2023-03-03 09:08:01
Original
1027 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?

// 直接用函数
>>> array_count_values($a)
=> [
     2 => 1,
     1 => 3,
     4 => 2,
     7 => 1,
     9 => 1,
   ]
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
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
Latest Issues
php data acquisition?
From 1970-01-01 08:00:00
0
0
0
PHP extension intl
From 1970-01-01 08:00:00
0
0
0
How to learn php well
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template