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 に答える