gpt4 book ai didi

php - 计算对象数组的列中某个值的出现次数

转载 作者:IT王子 更新时间:2023-10-28 23:54:41 25 4
gpt4 key购买 nike

有谁知道如何计算这个数组中“照片”的出现次数:

    Array ( 
[0] => stdClass Object ( [type] => photo [id] => 1404781893036 [created_time] => 2012-03-02T07:58:23+0000 )
[1] => stdClass Object ( [type] => photo [id] => 14047818930362 [created_time] => 2012-03-01T14:58:53+0000 )
[2] => stdClass Object ( [type] => status [id] => 1404781893036 [created_time] => 2012-03-01T09:49:40+0000 )
[3] => stdClass Object ( [type] => status [id] => 14047818930362 [created_time] => 2012-03-01T09:36:04+0000 )
[4] => stdClass Object ( [type] => photo [id] => 14047818930362 [created_time] => 2012-02-28T07:03:25+0000 )
[5] => stdClass Object ( [type] => photo [id] => 1404781893036 [created_time] => 2012-02-27T09:15:34+0000 )
[6] => stdClass Object ( [type] => photo [id] => 14047818930362 [created_time] => 2012-02-27T07:32:13+0000 )
[7] => stdClass Object ( [type] => status [id] => 1404781893036 [created_time] => 2012-02-25T09:36:57+0000 )
[8] => stdClass Object ( [type] => photo [id] => 1404781893036 [created_time] => 2012-02-23T08:46:43+0000 )
[9] => stdClass Object ( [type] => status [id] => 1404781893036 [created_time] => 2012-02-22T21:04:30+0000 )
[10] => stdClass Object ( [type] => status [id] => 1404781893036 [created_time] => 2012-02-21T20:38:27+0000 )
[11] => stdClass Object ( [type] => photo [id] => 1404781893036 [created_time] => 2012-02-21T07:22:44+0000 )
[12] => stdClass Object ( [type] => status [id] => 14047818930362 [created_time] => 2012-02-20T08:32:46+0000 )
[13] => stdClass Object ( [type] => status [id] => 1404781893036 [created_time] => 2012-02-17T15:00:11+0000 ) )

最佳答案

要计算多维数组中字符串的匹配出现次数,您需要遍历每个数组元素并匹配字符串并增加计数。类似地@Dor 建议

$count = 0;
foreach ($array as $item) {
if ($item->type === 'photo') {
$count++;
}
}

如果您想在一维数组中实现相同的效果,那么这非常简单。您可以使用array_count_values PHP 数组函数如下所述。

<?php
$array = array(1, "test", 1, "php", "test");
print_r(array_count_values($array));
?>

上面的例子会输出:

Array
(
[1] => 2
[test] => 2
[php] => 1
)

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

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