4

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()->elements->getCriteria(ElementType::Category);
$criteria->group = 'groupHandle';
$array = $criteria->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!

Matt Stein
  • 4,006
  • 3
  • 26
  • 57
Sander Van Keer
  • 213
  • 2
  • 8

1 Answers1

1

You might just have to do it yourself :)

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

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

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

Fuglsetrampen
  • 436
  • 2
  • 13