gpt4 book ai didi

php - 计算一个数组中某个值在另一个数组中出现的次数

转载 作者:行者123 更新时间:2023-12-02 22:32:58 26 4
gpt4 key购买 nike

我有一组看起来像这样的人:

$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
)
)

最佳答案

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

}

更新:另一种解决方案使用array_maparray_reduce 和不错的三元 运算符。它比使用 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);

关于php - 计算一个数组中某个值在另一个数组中出现的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11921817/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com