0

I have an array of categories that looks something like

array(
  array(
    'id' => '1',
    'path' => '1',
    'children_count' => '16',
    'name' => 'A'
  ),
  array(
    'id' => '3',
    'path' => '1/2/3',
    'children_count' => '0',
    'name' => 'C'
  ),
  array(
    'id' => '2',
    'path' => '1/2',
    'children_count' => '9',
    'name' => 'B'
  ),
  array(
    'id' => '4',
    'path' => '1/2/4',
    'children_count' => '0',
    'name' => 'D'
  )
)

What I'm trying to build is a hierarchal array (the path key shows the relation based on id), so the output is in the correct order (root parent first, then children, then more children) and indent the name based on how far down in the child is. The end result should look something like:

A
-B
--C
--D

Here's what I have so far, but it's obviously not working

$categoryTree = array();

foreach ($categories as $category) {

    $categoryTree[(string)$category['path']] = str_repeat("-", substr_count($category['path'], "/")) . $category['name'];
}

ksort($categoryTree);

var_export($categoryTree);

Which comes out to:

array (
  '1/2' => '-B',
  '1/2/3' => '--C',
  '1/2/4' => '--D',
  1 => 'A'
)

How can I get these in the correct order? (and if siblings could be ordered by id that would be dandy too)

2 Answers 2

1

This is based on One Trick Pony's answer, but correctly handles IDs with more than one digit.

foreach ($categories as $category)
  $output[$category['path']] =
    str_repeat('-', substr_count($category['path'], '/')) . $category['name'];

$paths = array_keys($output);
natsort($paths);

foreach ($paths as $path) {
  echo $output[$path], "\n";
}
Sign up to request clarification or add additional context in comments.

Comments

1

Count the number of slashes to generate the value prefixes, then sort by path (key) ?

foreach ($categories as $category)
  $output[$category['path']] =
    str_repeat('-', substr_count($category['path'], '/')) . $category['name'];

ksort($output, SORT_STRING);

2 Comments

Will this group items in the same part of the hierarchy together? E.g. if you have 1/2, 1/5, 1/2/3, 1/2/4, 1/5/6, 1/5/7.
Yes, isn't that the intended output? (1/2, 1/2/3, 1/2/4, 1/5...)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.