1

我是 PHP 新手,不确定 PHP 中的引用是如何工作的,因为它与 C++ 和 Java 截然不同。

基本上我有一个循环查找“标签”递归。我想要该数组元素的位置,然后添加我将另一个数组作为“标签”内的“标签”推送到它,因为在我的情况下,我有标签、子标签、子子标签......

这是代码:

private function organize_tags(&$tags = NULL)
{
if ($tags === NULL)
{
    return;
}


$organized_tags = array();

$highest_tag_level = -1;
foreach ($tags as $tag)
{
    if($tag['level'] > $highest_tag_level)
    {
        $highest_tag_level = $tag['level'];
    }
}

$current_tag_level = 0;
foreach ($tags as $key => $tag)
{
    if($tag['level'] == $current_tag_level)
    {
        array_push($organized_tags,$tag);
        unset($tags[$key]);
    }
}
$current_tag_level++;

while ($current_tag_level <= $highest_tag_level)
{
   foreach ($tags as $tag)
   {
        if($tag['level'] == $current_tag_level)
        {
            $tag_to_find = $tag['upper_tag'];

            $parent_tag = $this->find_tag($organized_tags, $tag_to_find);


            if($parent_tag != null)
            {
                if(!is_array($parent_tag['tag']))
                {
                    $parent_tag['tag'] = array();
                }
                array_push($parent_tag['tag'], $tag);
            }
        }
    }
    $current_tag_level++;
}

$tags = $organized_tags;

}



private function find_tag(&$tags, &$desired_tag_id)
{
    $ret = NULL;
    foreach($tags as $tag)
    {
        if($tag['id'] == $desired_tag_id)
        {
            return $tag;
        }
        else if (count($tag['tag']) > 0)
        {
            $ret = $this->find_tag($tag, $desired_tag_id);
            if($ret !== NULL)
            {
                return $ret;
            }
        }

    }
    return $ret;
}

如果有人可以帮助告诉我如何获得此插入,我会非常高兴。

4

1 回答 1

0

所以我创建了一种低效的方法来获取结果并插入它们。我使用这段代码从这里插入数组

无论如何这里是代码:

    if ($tags === NULL)
    {
        return;
    }

    $organized_tags = array();

    $highest_tag_level = -1;
    foreach ($tags as $tag)
    {
        if ($tag['level'] > $highest_tag_level)
        {
            $highest_tag_level = $tag['level'];
        }
    }

    $current_tag_level = 0;
    foreach ($tags as $tag)
    {
        if ($tag['level'] == $current_tag_level)
        {
            array_push($organized_tags, $tag);
        }
    }
    $current_tag_level++;

    foreach ($tags as $tag)
    {
        foreach ($organized_tags as $o_tag)
        {
            if ($tag['upper_tag'] == $o_tag['id'])
            {
                $this->array_insert($organized_tags,$tag,(array_search($o_tag,$organized_tags)+1));
            }
        }
    }
    return $organized_tags;

希望有人觉得这很有用:D

于 2013-10-09T11:40:30.843 回答