我有以下数组结构:
| ID | CategoryName | ParentID
_________________________________
1 | Movies | -1
_________________________________
2 | Series | -1
_________________________________
3 | ActionMovies | 1
_________________________________
4 | HorrorMovies | 1
_________________________________
5 | ComedySeries | 2
_________________________________
6 | TVShows | -1
我的目标是达到以下结构
目标:
| ID | CategoryName | ParentID
_________________________________
1 | Movies | -1
_________________________________
3 | ActionMovies | 1
_________________________________
4 | HorrorMovies | 1
_________________________________
2 | Series | -1
_________________________________
5 | ComedySeries | 2
_________________________________
6 | TVShows | -1
或用文字解释:
- 父类别有
ParentID = -1
(示例电影) - 所有类别均保留其原始 ID 号
- 应直接列在其 ParentCategory 之后(示例 ActionMovies)
- RootCategories without Children,列在数组的末尾。(例如电视节目)
我怎样才能用 PHP 做到最好?我无权访问原始的 Mysql 查询,所以这不是一个选项:)
我已经开始使用此代码,但我不确定它是正确的路径,并且只需最少的努力/可读性
$tmpList = Categories_Models_Main::getAllCategories();
$categoryData = array();
foreach ($tmpList as $index => $categoryObject) {
$categoryData[] = array('id' => $categoryObject->id,
'CategoryName' => $categoryObject->parentId,
'name' => $categoryObject->name);
}
///let us assume $categoryData is original state.
///Beginning of manipulation and re-sorting of $tmpList
foreach ($categoryData as $key => $value) {
$mainId[$key] = $value['id'];
$parentId[$key] = $value['parentId'];
}
array_multisort($parentId, $mainId, $categoryData);