简体   繁体   中英

How to count repeated values from an array or json in php

I would like to know how to tell the value of an array or json. Example: I want to count the value of the item GRUPO_OK = SIM and MRS_central = 1001.

Output:

MRS_central: "1001" => 2 GRUPO_OK: "SIM" => 3

Example array

Array ( [data] => Array ( [0] => Array ( [MRS_central] => 1003 [MRS_ipsat] => [GRUPO_OK] => NÃO ) [1] => Array ( [MRS_central] => 1001 [MRS_ipsat] => [GRUPO_OK] => SIM ) [2] => Array ( [MRS_central] => 1001 [MRS_ipsat] => [GRUPO_OK] => SIM ) [3] => Array ( [MRS_central] => 1002 [MRS_ipsat] => 10.4.0.253 [GRUPO_OK] => SIM ) ) )

Example json

{
data: [
{
MRS_central: "1001",
MRS_ipsat: "",
GRUPO_OK: "SIM"
},
{
MRS_central: "1001",
MRS_ipsat: "",
GRUPO_OK: "SIM"
},
{
MRS_central: "1003",
MRS_ipsat: "",
GRUPO_OK: "SIM"
},
{
MRS_central: "1002",
MRS_ipsat: "10.4.0.253",
GRUPO_OK: "NÃO"
}
]
}

If you have array_column() , you can extract each column. Then, you can use array_count_values() to count how many times a value appears in an array.

$mrs_grupo = array_column($arr['data'], 'GRUPO_OK');
$count = array_count_values($mrs_grupo);

print_r($count);


//RESULT
array(2) {
  ["SIM"]=>
  int(3)
  ["NÃO"]=>
  int(1)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM