1

假设我有以下数组:

Array
(
[0] => Array
    (
        [category_id] => 1
        [name] => foo
        [parent_id] => 0
    )

[1] => Array
    (
        [category_id] => 2
        [name] => bar
        [parent_id] => 1
    )

[2] => Array
    (
        [category_id] => 3
        [name] => baz
        [parent_id] => 0
    )

[3] => Array
    (
        [category_id] => 4
        [name] => test
        [parent_id] => 2
    )
[4] => Array
    (
        [category_id] => 5
        [name] => test2
        [parent_id] => 4
    )

)

我正在尝试获得以下输出:

foo
foo > bar
baz
foo > bar > test
foo > bar > test > test2

我想我已经对我脑海中的伪代码进行了排序,但想不出我将如何将它实际变成代码:

$arr = array();
foreach($categories as $category) {    
    if ($category['parent_id'] > 0) {
        $x = find where $categories['category_id'] == $cat['parent_id'];
        $arr[] = $x['name'].' > '.$category['name'];
        // somehow repeat till parent id is 0
    } else {
        $arr[] = $category['name'];
    }
}

有人有想法吗?谢谢

4

1 回答 1

5

这是我根据您的数组制作的函数:

function findParents($array, $parentId, $reset = true) {
  static $breadcrumbs;
  // reset path on every new lookup
  if ($reset == true) {
    $breadcrumbs = array();
  }

  foreach($array as $category) {
    if ($parentId == $category['category_id']) {
      // append the name of the category
      $breadcrumbs[] = $category['name'];

      // if a parent exists recursively call this function until no more parent is found
      if ($category['parent_id'] > 0) {
        findParents($array, $category['parent_id'], false);
      }
    }
  }
  // because the function goes the path from in to out, the array needs to be reversed
  return array_reverse($breadcrumbs);
}

用法:

foreach($categories as $category) {
  // find all parents to the current category
  $parents = findParents($categories, $category['category_id']);

  echo implode(' > ', $parents);
  echo PHP_EOL;
}

输出是:

foo
foo > bar
baz
foo > bar > test
foo > bar > test > test2
于 2012-04-22T17:48:22.067 回答