PHP 计算对象属性出现次数
我有一个如下所示的 PHP 对象,我想知道获取属性 'typeId' = 3 的对象计数的最简单方法是什么
Array
(
[0] => ABC Object
(
[id] => 13
[typeId] => 3
[sortOrder] => 0
)
[1] => ABC Object
(
[id] => 12
[typeId] => 2
[sortOrder] => 0
)
[2] => ABC Object
(
[id] => 14
[typeId] => 4
[sortOrder] => 0
)
[3] => ABC Object
(
[id] => 15
[typeId] => 3
[sortOrder] => 0
)
)
I have a PHP object like below and all I want to know whats the the easiest way to get a count of objects where the property 'typeId' = 3
Array
(
[0] => ABC Object
(
[id] => 13
[typeId] => 3
[sortOrder] => 0
)
[1] => ABC Object
(
[id] => 12
[typeId] => 2
[sortOrder] => 0
)
[2] => ABC Object
(
[id] => 14
[typeId] => 4
[sortOrder] => 0
)
[3] => ABC Object
(
[id] => 15
[typeId] => 3
[sortOrder] => 0
)
)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
一个简单的
foreach
计数器应该可以做到:不需要使事情过于复杂
A simple
foreach
counter should do:No need to over complicate things
从我的角度来看,一个更好的解决方案是使用 array_filter 函数:(
注意:内联函数仅从 PHP 5.3 开始工作)
From my point of view, a much nicer solution is to use the
array_filter
function:(note: inline functions only work since PHP 5.3)
只需创建一个名为
objectCount
或类似变量的临时变量,循环遍历数组,当找到 typeId 等于 3 的对象时,将 1 添加到objectCount
中。Just create a temporary variable called
objectCount
or something similar, loop through your array and when you find an object where the typeId equals 3 add 1 toobjectCount
.