ProLuck
ProLuck

Reputation: 375

how to count nested object inside array in php

I have data like this :

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"},
   ],
]

I wanna ask how to know the length of the second data, I already try using nested loop but the result is not same with my expectation my data come like this :

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"},
]

and when I try to count all my data the result : 9, and how to count my total object inside my array? Expectation Result :

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

Upvotes: 0

Views: 835

Answers (1)

lagbox
lagbox

Reputation: 50491

You can use array_map (which in this case is more than sufficient enough):

array_map('count', $fruits)

If you prefer you can use the Collection methods to help get your count from each "group":

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

Or shorter:

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

We create a Collection from the array and use the map method to iterate through each "group" (element of that array) and return the count of the "group". Then to get the array from the Collection, all.

PHP.net Manual - Array Functions - array_map

Laravel 8.x Docs - Collections - Available Methods - map

Laravel 8.x Docs - Collections - Available Methods - all

Upvotes: 3

Related Questions