Store categories in array by level in controller I'm making a plugin and I need to get an array from a certain category group where the levels of the array are the same as the level of the categories in the group.

So I used the following code to get all categories in a group.

$criteria = craft()-&gt;elements-&gt;getCriteria(ElementType::Category);
$criteria-&gt;group = 'groupHandle';
$array = $criteria-&gt;find();`


This works fine but I want to create something like this:

$array[
    level1:[ 
        level2[
            level3,
            level3,
        ],
        level2[], 
        level2[]
    ],
    level1:[ 
        level2[],
        level2[], 
        level2[]
    ]
]


I hope you get the idea...
I could make a foreach in a foreach in a foreach but that's not very classy.
Thanks in advance!
You might just have to do it yourself :)

$criteria = craft()-&gt;elements-&gt;getCriteria(ElementType::Category);
$criteria-&gt;group = 'groupHandle';
$categories = $criteria-&gt;find();
$sortedCategories = [];

foreach ($categories as $category) {
  if (!isset($sortedCategories[$category-&gt;level]) {
    $sortedCategories[$category-&gt;level] = [];
  }
  $sortedCategories[$category-&gt;level][] = $category;
}
var_dump($sortedCategories);


NOTE: I haven't tested this code, but in theory it should do the trick :)