我试图从未定义深度的php多维数组中获得附加在友好url上的完整字符串。类似于Wordpress的功能。结果就像parent/son/grandson
。下面是一个数组的例子:
Array
(
[0] => Array
(
[id] => 26
[slug] => animals
[children] => Array
(
[0] => Array
(
[id] => 29
[slug] => insects
[children] => Array
(
[0] => Array
(
[id] => 32
[slug] => grasshoppers
)
)
)
[1] => Array
(
[id] => 28
[slug] => mammals
[children] => Array
(
[0] => Array
(
[id] => 30
[slug] => dogs
)
[1] => Array
(
[id] => 31
[slug] => horses
)
)
)
)
)
[1] => Array
(
[id] => 27
[slug] => minerals
[children] => Array
(
[0] => Array
(
[id] => 33
[slug] => salt
)
)
)
)
我想调用这样的函数:
$full_slug = getFullSlug('dogs', $array);
$full_slug的内容为:
"animals/mammals/dogs"
经过一些研究后,我发现了在递归方法上使用array_unshift的类似案例的例子,但我无法为我自己的特定案例提供工作。如果对getFullSlug()函数有任何帮助,我将不胜感激!
使用递归很容易做到这一点:
function getFullSlug($key, $array) {
foreach($array as $node) {
if($key == $node['slug']) { //Found it on this node
return $node['slug'];
}
else //Search depth first
{
if (isset($node['children']) && is_array($node['children']) && !empty($node['children']) ) {
$subSlug = getFullSlug($key, $node['children']);
if(!empty($subSlug)) //If it was found
{
return $node['slug'].'/'.$subSlug;
}
else //Look at the next sibling
{
continue;
}
} else { // This is a leaf, and it wasn't found
continue;
}
}
}
return ''; //Failed to find it.
}
当然,这也可以添加到类中。如果你这样做,那么你需要更新getFullSlug调用到$this->getFullSlug(....)。
这是我测试它的鼻涕虫数组,应该和你提到的完全一样:
$slugs = array(
array(
'id' => 26,
'slug' => 'animals',
'children' => array(
array(
'id' => 29,
'slug' => 'insects',
'children' => array(
array(
'id' => 32,
'slug' => 'grasshoppers'
)
)
),
array(
'id' => 28,
'slug' => 'mammals',
'children' => array(
array(
'id' => 30,
'slug' => 'dogs'
),
array(
'id' => 31,
'slug' => 'horses'
)
)
)
)
),
array(
'id' => 27,
'slug' => 'minerals',
'children' => array(
array(
'id' => 33,
'slug' => 'salt'
)
)
)
);
最后,下面是一些使用函数的代码:
echo getFullSlug('animals', $slugs).'<br>';
echo getFullSlug('insects', $slugs).'<br>';
echo getFullSlug('grasshoppers', $slugs).'<br>';
echo getFullSlug('mammals', $slugs).'<br>';
echo getFullSlug('dogs', $slugs).'<br>';
echo getFullSlug('horses', $slugs).'<br>';
echo getFullSlug('minerals', $slugs).'<br>';
echo getFullSlug('salt', $slugs).'<br>';
和相应的输出,如预期的:
animals
animals/insects
animals/insects/grasshoppers
animals/mammals
animals/mammals/dogs
animals/mammals/horses
minerals
minerals/salt
希望这对你有帮助!
注:要检查一个段符是否存在,可以使用empty()。
对于上面的例子,
$url = getFullSlug('platypus', $slugs);
if(empty($url))
echo "Slug doesn't exist";
else
echo "New url: $url";
如果$slugs多维数组中没有鸭嘴兽,将打印"Slug doesn't exist";如果鸭嘴兽存在,
将打印"New url: animals/哺乳动物/鸭嘴兽"。像这样的东西应该为您工作:
public function getFullSlug($key, $array) {
foreach($array as $arrayKey => $arrayValue) {
if (is_array($arrayValue)) {
return $arrayKey . '/' . $this->getFullSlug($key, $arrayValue);
} else if ($arrayValue === $key) {
return $arrayValue;
}
throw InvalidArguementException("full slug could not be built for $key", 404);
}
}