Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

230
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda