如何为PHP数组获取类似SQL的HAVING和GROUP BY?

时间:2023-01-24 22:26:00

Is there a PHP code snippet or a built in array function that would do kind of like what a sql statement with having and group by does? That is removing the dups and counting the occurrences and giving you back an array that you can use for reporting/debugging purposes.

是否有一个PHP代码片段或内置数组函数,它会像具有having和group by的sql语句一样?这就是删除重复并计算出现次数并返回一个可用于报告/调试目的的数组。

An example may clarify;

一个例子可以澄清;

say your array is like this

说你的阵列是这样的

Array (
['0'] => usa
['1'] => minnesota
['2'] => california
['3'] => san fransisco
['4'] => los angeles
['5'] => san fransisco
['6'] => malibu
['7'] => malibu
['8'] => malibu
['9'] => usa
}

and you want something back like this, or something to this effect..

你想要像这样的东西,或者这种效果的东西......

Array (
['usa'] => 2
['minnesota'] => 1
['california'] => 1
['san fransisco'] => 2
['los angeles'] => 1
['malibu'] => 3
}

3 个解决方案

#1


2  

http://www.php.net/manual/en/function.array-count-values.php

You can use the following code to do this:

您可以使用以下代码执行此操作:

array_count_values ($myArray)

#2


1  

Doing it manually:

手动完成:

$new = array();
foreach($array as $key => $val) {
  if (!isset($new[$key]) {
    $new[$key] = 0;
  }
  $new[$key]++;
}

#3


1  

Use array_count_values() to get the number of duplicates

使用array_count_values()来获取重复的数量

$array = array(...);
$duplicate = array_count_values($array);

#1


2  

http://www.php.net/manual/en/function.array-count-values.php

You can use the following code to do this:

您可以使用以下代码执行此操作:

array_count_values ($myArray)

#2


1  

Doing it manually:

手动完成:

$new = array();
foreach($array as $key => $val) {
  if (!isset($new[$key]) {
    $new[$key] = 0;
  }
  $new[$key]++;
}

#3


1  

Use array_count_values() to get the number of duplicates

使用array_count_values()来获取重复的数量

$array = array(...);
$duplicate = array_count_values($array);