如何打破 PHP 面包屑循环?

how to break out of PHP breadcrumb loop?

我正在使用以下函数显示数组中的类别面包屑

function breadcrumber($array, $id) {
    // declare the storage variable without losing elements during recursion
    static $result = [];  
    if (isset($array[$id])) {  // if target exists
        $result[] = $array[$id]['name'];  // store title text
        $parent = $array[$id]['parentID'];  // assign new target
        unset($array[$id]);  // remove possibility of an infinite loop
        breadcrumber($array, $parent);  // recurse
    }
    return array_revers($result);
}

呼叫者:

echo implode(' -> ',breadcrumber(array_column($category,NULL,'id'),4));

数组:

$category = array(
    1 => array(
        'id' => 1,
        'parentID' => 0,
        'name' => 'SUV auto parts'
    ),
    2 => array(
        'id' => 2,
        'parentID' => 1,
        'name' => 'Engine Related'
    ),
    3 => array(
        'id' => 3,
        'parentID' => 2,
        'name' => 'Spark Plugs'
    ),
    4 => array(
        'id' => 4,
        'parentID' => 2,
        'name' => 'Engine Oil'
    ),
    5 => array(
        'id' => 5,
        'parentID' => 1,
        'name' => 'Body related'
    ),
    6 => array(
        'id' => 6,
        'parentID' => 0,
        'name' => 'Sedan auto parts'
    ),
    7 => array(
        'id' => 7,
        'parentID' => 6,
        'name' => 'Engine Related'
    ),
);

这适用于单个页面/项目页面

SUV auto Parts -> Engine Related -> Engine Oil

但是,当我尝试在一页中显示特定类别的所有内容时,此函数输出如下

SUV auto Parts -> Engine Related -> Engine Oil -> SUV auto Parts -> Engine Related -> Engine Oil

循环结束,

例如;我在机油下有3个项目,用小盒子在一页上显示,我期待它,


项目标题 1

迷你描述

商品价格

SUV auto Parts -> Engine Related -> Engine Oil



项目标题 2

迷你描述

商品价格

SUV auto Parts -> Engine Related -> Engine Oil



项目标题 3

迷你描述

商品价格

SUV auto Parts -> Engine Related -> Engine Oil


相反,我得到的输出是


项目标题 1

迷你描述

商品价格

SUV auto Parts -> Engine Related -> Engine Oil



项目标题 2

迷你描述

商品价格

SUV auto Parts -> Engine Related -> Engine Oil -> SUV auto Parts -> Engine Related -> Engine Oil



项目标题 3

迷你描述

商品价格

SUV auto Parts -> Engine Related -> Engine Oil -> SUV auto Parts -> Engine Related -> Engine Oil -> SUV auto Parts -> Engine Related -> Engine Oil


我无法解决这个问题,如果有人能提供任何解决方案来解决这个问题,我将不胜感激。

当您在函数中声明静态变量时,它会永远记住它的值。在您第一次调用时它工作正常,因为 $result 是空的。当你第二次调用它时,第一次调用的结果仍然在那里,只是附加了新的结果。这就是面包屑越来越长的原因。

我重写了你的方法,没有使用静态变量(一不小心就容易出错)

function breadcrumber($array, $id)
{
    if (!isset($array[$id])) return [];

    $result = [];
    $result[] = $array[$id]['name'];  // store title text
    $parent = $array[$id]['parentID'];  // assign new target
    unset($array[$id]);  // remove possibility of an infinite loop

    // prepend the recursion result to the already existing results (effectively replacing the array_reverse)
    return array_merge(breadcrumber($array, $parent), $result);  // recurse
}