سؤال

I have a multidimensional menu saved in MySQL. Table look like:

id name parent_id

The table is huge. I don't want to run hundreds of mysql_query() so I started with this:

$result = mysql_query("SELECT * FROM test");
$arrs = array();

while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
    $arrs[] = $row;
}

function build_tree($arrs, $parent_id=0, $level=0) {
    foreach ($arrs as $arr) {
        if ($arr['parent_id'] == $parent_id) {
            echo str_repeat("-", $level)." ".$arr['name']."<br />";
            build_tree($arrs, $arr['id'], $level+1);
        }
    }
}

build_tree($arrs);

This works just fine, but how do I modify this to print all parent_ids for each post? Almost like breadcrumbs.

هل كانت مفيدة؟

المحلول

Instead of passing in only one parent_id, you can pass in an array of parent_ids. You can append the current parent_id into this array before the recursive call, and remove it after the recursive call.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top