我有一群看起来像这样的人:
$people =
Array
(
[0] => Array
(
[email] => NameSurname@example.com
[name] => Name Surname
[count] => 0
)
[1] => Array
(
[email] => Name2Surname@example.com
[name] => Name2 Surname
[count] => 0
)
)
我有一个数组,它是MySQL查询的结果,如下所示:
$query=
Array
(
[0] => Array
(
[email] => NameSurname@example.com
[name] => Name Surname
)
[1] => Array
(
[email] => Name2Surname@example.com
[name] => Name2 Surname
)
[2] => Array
(
[email] => NameSurname@example.com
[name] => Name Surname
)
)
对于$ people中的每个电子邮件地址,我希望$people['count']
等于$ query中该电子邮件地址的出现次数。
我已经尝试了许多方法来做到这一点,而且我没有得到理想的结果。
为避免疑义,基于上述示例的最终结果应如下所示:
$people =
Array
(
[0] => Array
(
[email] => NameSurname@example.com
[name] => Name Surname
[count] => 2
)
[1] => Array
(
[email] => Name2Surname@example.com
[name] => Name2 Surname
[count] => 1
)
)
答案 0 :(得分:4)
foreach ($people as $key => $man) { // iterating through each man
$_occurences = 0;
foreach ($query as $_item) // iterating through each result in the result set
if ($_item['email'] == $man['email']) // comparing current man to each result item
$_occurences ++;
$people[$key]['count'] = $_occurences; // saving number of occurrences in the `count` key
}
UPD:使用array_map
,array_reduce
和不错ternary
运算符的另一个解决方案。它比foreach
慢,但紧凑和专业两倍。
它更慢(在性能方面)因为。函数调用开销,但在“小”迭代量上,这种下降可以忽略不计。它将更新$people
数组而不重新分配它。我们通过引用传输了每个&$man
。
array_map(function (&$man) use ($query) {
$man['count'] = array_reduce($query, function ($count, $row) use ($man) {
return ($row['email'] === $man['email']) ? ++$count : $count ;
}, 0);
}, $people);
答案 1 :(得分:1)
不确定这是否正是您所需要的。但您可以更改正在运行的查询:
SELECT COUNT(name) as cnt, name,email FROM table_name GROUP BY name;
然后$query
数组将如下所示:
$query=
Array
(
[0] => Array
(
[email] => NameSurname@example.com
[name] => Name Surname
[cnt] => 2
)
[1] => Array
(
[email] => Name2Surname@example.com
[name] => Name2 Surname
[cnt] => 1
)
)
然后您可以在数组上运行,只需获取cnt
数组中每个项目的$query
。