3v4l.org

run code in 300+ PHP versions simultaneously
<?php // The hierarcical structure of the categories is: // // Domain // - Category // - - Subcategory class simulating_categories_object{ public $id; public $parent; public $slug; function __construct($id,$parent,$slug){ $this->id = $id; $this->parent = $parent; $this->slug = $slug; } } global $catobj; $catobj = []; $catobj[] = new simulating_categories_object(1,0,'domain1'); $catobj[] = new simulating_categories_object(2,0,'domain2'); $catobj[] = new simulating_categories_object(3,0,'domain3'); $catobj[] = new simulating_categories_object(4,1,'category1'); $catobj[] = new simulating_categories_object(5,1,'category2'); $catobj[] = new simulating_categories_object(6,1,'category3'); $catobj[] = new simulating_categories_object(7,4,'subcategory1'); $catobj[] = new simulating_categories_object(8,4,'subcategory2'); $catobj[] = new simulating_categories_object(9,2,'category555'); $catobj[] = new simulating_categories_object(10,9,'subcategory666'); $catobj[] = new simulating_categories_object(11,3,'category777'); function get_the_parent_id_of_a_given_element_id($id){ global $catobj; foreach($catobj as $category){ if($category->id == $id) return $category->parent; } } echo "<pre>"; //print_r($catobj); echo "</pre>"; foreach($catobj as $element) { if($element->parent == 0){ // our $element is a domain. echo "This element is a domain. The slug of the element is ".$element->slug."<br>"; continue; } $element_parent_id = get_the_parent_id_of_a_given_element_id($element->parent); if($element_parent_id == 0){ // our $element is a category echo "This element is a category. The slug of the element is ".$element->slug."<br>"; continue; } $element_parent_parent_id = get_the_parent_id_of_a_given_element_id($element_parent_id); if($element_parent_parent_id == 0){ // our $element is a subcategory echo "This element is a subcategory. The slug of the element is ".$element->slug."<br>"; } } $result = ['domain1' => [ 'category1' => ['subcategory1','subcategory2'], 'category2' => [], 'category3' => [] ], 'domain2' => [ 'category555' => ['subcategory666'] ], 'domain3' => [ 'category777' => [] ] ]; echo "<pre>"; print_r($result); echo "</pre>";

preferences:
70.24 ms | 402 KiB | 5 Q