PHP中有如下数组项:
0 => [
'name' => 'retail',
'id' => 1,
'following' => null
],
1 => [
'name' => 'industry',
'id' => 2,
'following' => 3
],
2 => [
'name' => 'entertainment',
'id' => 3,
'following' => 1
],
3 => [
'name' => 'sports',
'id' => 4,
'following' => null
],
4 => [
'name' => 'construction',
'id' => 5,
'following' => null
],
5 => [
'name' => 'music',
'id' => 6,
'following' => 5
]
...
和我想链每个项目的名称和顺序,他们从父到子。上面的示例将给出结果:
[
0 => 'industry / entertainment / retail',
1 => 'sports',
2 => 'music / construction'
]
每个条目可以有尽可能多的子条目,并且条目的顺序是随机的。这几天来我一直在做这个,但我仍然没有成功。有什么需要帮助的吗?
- 创建/格式化
followings
为id: [following_id]
的数组 - 链
followings
递归 - 从下列链中创建字符串
$items = [
0 => [
'name' => 'retail',
'id' => 1,
'following' => null
],
1 => [
'name' => 'industry',
'id' => 2,
'following' => 3
],
2 => [
'name' => 'entertainment',
'id' => 3,
'following' => 1
],
3 => [
'name' => 'sports',
'id' => 4,
'following' => null
],
4 => [
'name' => 'construction',
'id' => 5,
'following' => null
],
5 => [
'name' => 'music',
'id' => 6,
'following' => 5
]
];
// STEP 1
$followings = [];
foreach($items as $id => $data){
$item_id = $items[$id]['id'];
if(isset($items[$id]['following']))
$followings[$item_id] = [$items[$id]['following']];
else
$followings[$item_id] = [];
}
// STEP 2
function chain(&$arr, $i){
if(empty($arr[$i])){
return;
}
$last_follow_id = end($arr[$i]);
if(empty($arr[$last_follow_id])){
unset($arr[$last_follow_id]);
return;
}
chain($arr, $last_follow_id);
$arr[$i] = array_merge($arr[$i], $arr[$last_follow_id]);
unset($arr[$last_follow_id]);
}
foreach ($followings as $id => $follows) {
chain($followings, $id);
}
// STEP 3
foreach($followings as $first => $remaining){
if(empty($remaining)){
$followings[$first] = $items[$first - 1]['name'];
continue;
}
$chain = $items[$first - 1]['name'] . ' / ';
foreach($remaining as $r){
$chain .= $items[$r - 1]['name'] . ' / ';
}
$chain = substr($chain, 0, -3);
$followings[$first] = $chain;
}
// Reindex if needed
print_r(array_values($followings));