For example, I want to get the final parent class of the little black pig with ID 10. In the table, the parent_id is 9, but what I want to get is 5. Is there any way, or I want to judge a certain item? Record whether it belongs to the final parent class
仅有的幸福2017-06-06 09:56:07
There are 2 methods you can try:
Query all ids and parent_id, and then search, so that fixed sql statements can be cached.
Add a new field root_id to record the root node, so there is no need to search, just query it directly. You only need to query it once when inserting.
漂亮男人2017-06-06 09:56:07
$arr = array(
array(
'id' => 10,
'parent_id' => 9
),
array(
'id' => 9,
'parent_id' => 5
),
array(
'id' => 5,
'parent_id' => null
),
);
function getParentId($arr, $id = 10) {
foreach ($arr as $val) {
if($val['id'] == $id) {
if(!empty($val['parent_id'])) {
$id = $val['parent_id'];
getParentId($arr, $id);
}else {
return $id;
}
}
}
return $id;
}
echo getParentId($arr, 10);