Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

213
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda