categories()->split() as $category) { $categories[$category] = array( 'title' => $category, 'texts' => new Pages() ); } return $categories; } function fillCategoriesWithTexts($emptyCategories, $texts) { $filledCategories = $emptyCategories; foreach ($texts as $text) { try { $textCategory = $text->category()->value(); $filledCategories[$textCategory]['texts']->add($text); } catch (\Throwable $th) { throw new Exception(json_encode($th->getFile() . ' : ' . $th->getMessage())); } } // exclude empty categories return array_filter($filledCategories, function($category) { return count($category['texts']) > 0; }); } return function ($site) { $textsPage = $site->find('textes'); $years = $textsPage->children(); $texts = $years->children()->index(); $emptyCategories = createCategories($textsPage); $filledCategories = fillCategoriesWithTexts($emptyCategories, $texts); return $filledCategories; };