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!

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 :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.