我是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;
}
如果有人可以帮我告诉我如何插入,我会非常高兴。
答案 0 :(得分:0)
所以我创建了一种低效的方法来获取结果并插入它们。我使用这段代码从here
插入数组无论如何这里是代码:
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