Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

214
Views
Print parent child category path in "/" format like "parentCatId/childCatId/subChildCatId/so on"

I want to print category path in "/" format like "parentCatId/childCatId/subChildCatId/so on". I want to print all parent child categoryId in single path format.

$cats = array(
    array("catId" => 1, "parentId" => 0),
    array("catId" => 2, "parentId" => 1),
    array("catId" => 3, "parentId" => 1),
    array("catId" => 4, "parentId" => 2),
    array("catId" => 5, "parentId" => 2),
    array("catId" => 6, "parentId" => 3),
    array("catId" => 7, "parentId" => 3),
    array("catId" => 8, "parentId" => 4),
);

function getCatIdByParent($catArr, $catId, $catPath="/") {
   $parentCatId = $catArr[$catId]['parentId'];
   if($parentCatId == 0) {
       $catPath .= $catId."/";
       return $catPath;
   } else {
       $catPath .= $catId."/";
       $a = getCatIdByParent($catArr, $parentCatId, $catPath);
   }
   return $a;
}
foreach($cats as $catInfo) {
   $catArr[$catInfo['catId']] = $catInfo;
}
foreach($catArr as $catId => $catInfo) {
   $catArr2[] = getCatIdByParent($catArr, $catId);
}

This gives out :

Array
(
    [0] => /1/
    [1] => /2/1/
    [2] => /3/1/
    [3] => /4/2/1/
    [4] => /5/2/1/
    [5] => /6/3/1/
    [6] => /7/3/1/
    [7] => /8/4/2/1/
)

But I want to bellow output:

Array
(
    [0] => /5/2/1/
    [1] => /6/3/1/
    [2] => /7/3/1/
    [3] => /8/4/2/1/
)
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

You will have to make the 'rootParents' (0,1,2,3) as seperate indexes, with their id being the key, you then can use the 'outter' array keys as the rootParentID's and you get the wanted result.

Example:

$catsParents[0] = array(
                    array("catId" => 1, "parentId" => 0),
                    array("catId" => 2, "parentId" => 1),
                  );

$catsParents[1] = array (etc

foreach($catParents as $parent){
$parentId = key($parent);
// do your magic

}
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!