我有一系列文件夹/路径:我有一系列文件夹/路径: $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要怎么对数组元素进行分组
猜你喜欢
- Laravel balde模板文件中判断数据为空方法 2023-08-30
- laravel实现按月或天或小时统计mysql数据的方法 2023-02-22
- PHP实现微信支付(jsapi支付)流程步骤详解 2022-10-09
- php微信公众号开发之秒杀 2022-11-23
- PHP仿tp实现mvc框架基本设计思路与实现方法分析 2022-10-18
- laravel通用化的CURD的实现 2023-03-17
- 用nohup命令实现PHP的多进程 2023-09-02
- PHP中PDO事务处理操作示例 2022-10-15
- windows下9款一键快速搭建PHP本地运行环境的好工具(含php7.0环境) 2023-09-02
- PHP简单实现二维数组的矩阵转置操作示例 2022-10-02