繁体   English   中英

如何计算 php 中数组内的嵌套 object

[英]how to count nested object inside array in php

我有这样的数据:

array: [
   0: [
     0: {fruits: "apple", price: "15000"},
     1: {fruits: "orange", price: "12000"},
   ],
   1: [
     0: {fruits: "grape", price: "13000"},
     1: {fruits: "chery", price: "14000"},
     2: {fruits: "longan", price: "12000"},
   ],
   2: [
     0: {fruits: "manggo", price: "16000"},
     1: {fruits: "dragon fruit", price: "17000"},
     2: {fruits: "avocado", price: "18000"},
     3: {fruits: "coconut", price: "19000"},
   ],
]

我想问如何知道第二个数据的长度,我已经尝试使用嵌套循环,但结果与我的预期不同,我的数据如下:

array: [
  0: {fruits: "apple", price: "15000"},
  1: {fruits: "orange", price: "12000"},
  2: {fruits: "grape", price: "13000"},
  3: {fruits: "chery", price: "14000"},
  4: {fruits: "longan", price: "12000"},
  5: {fruits: "manggo", price: "16000"},
  6: {fruits: "dragon fruit", price: "17000"},
  7: {fruits: "avocado", price: "18000"},
  8: {fruits: "coconut", price: "19000"},
]

当我尝试计算所有数据the result: 9 ,以及如何计算数组中的总 object ? 预期结果:

array 0 = 2, array 1 = 3, array 2 = 4

您可以使用array_map (在这种情况下已经足够了):

array_map('count', $fruits)

如果您愿意,可以使用 Collection 方法帮助从每个“组”中获取计数:

collect($fruits)->map(fn ($i) => count($i))->all()

或更短:

collect($fruits)->map('count')->all()

我们从数组创建一个 Collection 并使用map方法遍历每个“组”(该数组的元素)并返回“组”的计数。 然后从 Collection 中获取数组, all .

PHP.net 手册 - 数组函数 - array_map

Laravel 8.x 文档 - Collections - 可用方法 - map

Laravel 8.x 文档 - Collections - 可用方法 - all

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM