[英]Finding the children of the sub-sub-category from a sub-category
我目前有一個代碼段,其中每個類別都可以找到子類別:
$categories = array_map(
function($child)
{
$child['children'] =
$this->getChildren(
$child['id'],
!empty($this->request->get['language_id']) ?
$this->request->get['language_id'] : 1
);
return $child;
}, $categories);
getChildren()
將遞歸地獲取一類的子級:
private function getChildren($parent_id, $language_id) {
$this->load->model('official/category');
$children =
$this->model_official_category->getCategoriesByParentId(
$parent_id,
$language_id
);
// For each child, find the children.
foreach ($children as $child) {
$child['children'] = $this->getChildren(
$child['id'],
$language_id
);
}
return $children;
}
當前,使用我在array_map()
lambda函數,將僅檢索子類別的子類別,因此,如果每個子類別都有其自己的子子類別,則不會將其保存到其子類別中。
給定我們擁有的子類別,如何顯示子類別?
我想用我的代碼做的事情是讓一個父母,得到它的孩子,然后將這些孩子中的每一個當作父母,然后遞歸地獲得它的孩子,但是我的JSON輸出並不反映這一點。 只有父母有孩子-子女沒有孩子(盡管我的數據庫中有他們)。
問題是您的遞歸foreach
循環將它檢索的子代分配給子代數據的副本 ,而不是子代數據本身。
要解決此問題,您可以使用引用子數據的foreach
循環,如下所示:
foreach ($children as &$child) {
但是 ,由於與PHP內部如何實現foreach
有關的多種原因(有關更多信息,請關注 ),因此使用for
循環會大大提高內存效率,因為這將避免很多復制操作-子數據的寫入副本:
for ($i = 0; isset($children[$i]); $i++) {
$children[$i]['children'] = $this->getChildren(
$children[$i]['id'],
$language_id
);
}
在這里,使用對象而不是數組來表示子數據可能是一個好主意,因為對象總是通過引用(種類)傳遞的,並且其行為將更像您最初期望的那樣。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.