Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

GodziLaravel's avatar

How to flat multidimensional array of objects ?

Hello ,

I have this multidimensional collection bellow and I would like to get all id values to have at the end an array like [7,201,66,17,15,93,88,4,502]

Thanks

[
  {
    "id": 7,
    "name": "Alvah Harris",
    "team_leader_of_with_descendants": [
      
    ]
  },
  {
    "id": 201,
    "name": "Prof. Walker Cronin",
    "team_leader_of_with_descendants": [
      {
        "id": 66,
        "team_leader_of_with_descendants": [
          
        ]
      },
      {
        "id": 17,
        "name": "Dr. Hosea Lueilwitz IV",
       
        "team_leader_of_with_descendants": [
          {
            "id": 15,
            
            "avatar": "1566561953_5d5fd6a1ac6b2.png",
            "team_leader_of_with_descendants": [
              
            ]
          },
          {
            "id": 93,
            "name": "Edyth Frami Sr.",
           
            "team_leader_of_with_descendants": [
              
            ]
          }
        ]
      }
    ]
  },
  {
    "id": 88,
    "name": "Guadalupe Simonis Jr.",
  
    "avatar": "user.jpg",
    "team_leader_of_with_descendants": [
      
    ]
  },
  {
    "id": 4,
    "name": "Axel Windler",
   
    "avatar": "user.jpg",
    "team_leader_of_with_descendants": [
      {
        "id": 502,
        "name": "Mostafa Abdellaoui",
       
        "team_leader_of_with_descendants": [
          
        ]
      }
    ]
  }
]
0 likes
5 replies
mstrauss's avatar

That makes sense, since flatten would remove the keys from the ids and hence, pluck will not pick up on them. Try just using the pluck method to see what that returns:

$ids = $collection->pluck('id');
Sinnbeck's avatar

I personally had a similar issue not long ago and I ended up creating these two collection helpers to make it work. You can change them to fit your data and add them to a service provider. Be aware that is expects that children are relations (I expect they are in your case as well)

Collection::macro('flattenTree', function() {
            $items = [];
            foreach ($this->items as $node) {
                $items = array_merge($items, $this->flattenNode($node));
            }

            return new static($items);
        });

        Collection::macro('flattenNode', function($node) {
            $items = [];
            $items[] = $node;
            foreach ($node->children as $childNode) {
                $items = array_merge($items, $this->flattenNode($childNode));
            }
            $node->unsetRelation('children');
            return $items;
        });

Please or to participate in this conversation.