我有一系列文件夹/路径:我有一系列文件夹/路径: $arr = Array( 0 = Array ( 'name' = 'aaa' ), 1 = Array ( 'name' = 'aaa\bbb' ), 2 = Array ( 'name' = 'aaa\bbb\ccc' ), 3 = Array
php">$arr = Array
(
0 => Array
(
'name' => 'aaa'
),
1 => Array
(
'name' => 'aaa\bbb'
),
2 => Array
(
'name' => 'aaa\bbb\ccc'
),
3 => Array
(
'name' => 'ddd'
)
);
我想将它转换为多维(树状)数组(保持结构:索引/键和值/名称):
aaa
bbb
ccc
ddd
有什么建议和方法吗?解决办法,尝试用如下代码:
$arr = array(
array('name' => 'aaa'),
array('name' => 'aaa\bbb'),
array('name' => 'aaa\bbb\ccc'),
array('name' => 'ddd'),
array('name' => 'ddd\zzz'),
array('name' => 'zzz'),
array('name' => 'ddd\zzz\fff'),
);
$new = array();
$helper = array();
foreach ($arr as $i => $entry) {
$parent =& $new;
/**
* One could use:
* explode(DIRECTORY_SEPARATOR, $entry['name'])
* 编程学习网 topstudy.com.cn
* instead of '\\' if you're dealing with file-structures
*/
foreach ($path = explode('\\', $entry['name']) as $ii => $element) {
$subPath = implode('.', array_slice($path, 0, $ii + 1));
if (isset($helper[$subPath])) {
$parent =& $helper[$subPath];
continue;
}
$parent[$i] = array('name' => $element);
$helper[$subPath] =& $parent[$i];
}
}
print_r($new);
输出结果为:
Array
(
[0] => Array
(
[name] => aaa
[1] => Array
(
[name] => bbb
[2] => Array
(
[name] => ccc
)
)
)
[3] => Array
(
[name] => ddd
[4] => Array
(
[name] => zzz
[6] => Array
(
[name] => fff
)
)
)
[5] => Array
(
[name] => zzz
)
)
沃梦达教程
本文标题为:php要怎么对数组元素进行分组
基础教程推荐
猜你喜欢
- 使用PHP开发留言板功能 2023-03-13
- thinkphp3.2.3框架动态切换多数据库的方法分析 2023-03-19
- 在Laravel中实现使用AJAX动态刷新部分页面 2023-03-02
- PHP获取MySQL执行sql语句的查询时间方法 2022-11-09
- PHP实现Redis单据锁以及防止并发重复写入 2022-10-12
- PHP命名空间简单用法示例 2022-12-01
- PHP中的错误及其处理机制 2023-06-04
- php array分组,PHP中array数组的分组排序 2022-08-01
- laravel ORM关联关系中的 with和whereHas用法 2023-03-02
- laravel 解决多库下的DB::transaction()事务失效问题 2023-03-08