我从一个服务数组得到如下:
0:
category_id: 21
parent_id: 17
name: Parent
url_key: parent
is_active: 1
position: 4
level: 3
children:
0:
category_id: 25
parent_id: 21
name: child1
url_key: child1
is_active: 1
position: 1
level: 4
children:
0:
category_id: 52
parent_id: 25
name: child1child1
url_key: child1child1
is_active: 1
position: 1
level: 5
children:
1:
category_id: 26
parent_id: 21
name: child2
url_key: child2
is_active: 1
position: 2
level: 4
children:
0:
category_id: 54
parent_id: 26
name: child2child1
url_key: child2child1
is_active: 1
position: 1
level: 5
children:
1:
category_id: 55
parent_id: 26
name: child2child2
url_key: child2child2
is_active: 1
position: 2
level: 5
children:
我需要遍历这个数组我不知道它能有多深并使用url_key变量生成url路径,例如:
parent
parent/child1
parent/child1/child1
parent/child2/child1
我试着用array_walk_recursive来做,但是我可以弄清楚。
任何帮助都会很感激。
谢谢
array_walk_recursive还不够聪明。你必须做出自己的决定。我做得很快,我相信它可以得到很大的改进:
<?php
$categories = array(
0 => array(
'url_key' => 'parent',
'children' => array(
0 => array(
'url_key' => 'child1',
'children' => array(
0 => array(
'url_key' => 'child1child1',
'children' => array()
)
)
),
1 => array(
'url_key' => 'child2',
'children' => array(
0 => array(
'url_key' => 'child2child1',
'children' => array()
),
1 => array(
'url_key' => 'child2child2',
'children' => array(
0 => array(
'url_key' => 'child2child2child1',
'children' => array()
),
)
),
)
)
)
)
);
$urls = array();
foreach ($categories as $category) {
$urls = $urls + buildUrls($category, $urls);
}
function buildUrls($category, &$urls, $url_parts = array()) {
$url_parts[] = $category['url_key'];
$urls[] = join('/', $url_parts);
if (!empty($category['children'])) {
foreach ($category['children'] as $child_category) {
$urls = $urls + buildUrls($child_category, $urls, $url_parts);
}
}
return $urls;
}
var_dump($urls);
输出:array (size=7)
0 => string 'parent' (length=6)
1 => string 'parent/child1' (length=13)
2 => string 'parent/child1/child1child1' (length=26)
3 => string 'parent/child2' (length=13)
4 => string 'parent/child2/child2child1' (length=26)
5 => string 'parent/child2/child2child2' (length=26)
6 => string 'parent/child2/child2child2/child2child2child1' (length=45)