0

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
2
  • you want a count of the number of elements in each group? Commented Dec 17, 2020 at 3:45
  • yes sir, I wanna count of the number of my element inside the group Commented Dec 17, 2020 at 3:46

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

4 Comments

okey sir, thanks for giving the answer from this question, and you giving the documentation too. precise, concise, and clear answer
@LuckALip np, I added a straight PHP option as well ... good luck and have fun
okey sure noted for me, thanks for everything
I agree with @lagbox sir, array_map is sufficient as map method of collection uses array_map in background

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.