Last active
July 12, 2019 05:55
-
-
Save crusj/c62c84ac58068da8673c37afa0b80b09 to your computer and use it in GitHub Desktop.
将有层级关系的php数组转换为层级数组
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
//需要数据的键与子项目id相同 | |
$arr = [ | |
1 => [ | |
"id" => 1, | |
"pid" => 0, | |
"value" => 1 | |
], | |
2 => [ | |
"id" => 2, | |
"pid" => 0, | |
"value" => 2 | |
], | |
3 => [ | |
"id" => 3, | |
"pid" => 1, | |
"value" => 1.1 | |
], | |
4 => [ | |
"id" => 4, | |
"pid" => 2, | |
"value" => 2.1 | |
], | |
]; | |
$levelArray = []; | |
foreach($arr as $key => $value){ | |
if($value['pid'] !== 0){ | |
$arr[$value['pid']]['sub'][] = &$arr[$key]; | |
}else{ | |
$levelArray[] = &$arr[$key]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment