php - How does Laravel's Baum obtain the final parent class id of a certain record?
某草草
某草草 2017-06-06 09:54:07
0
3
646

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

某草草
某草草

reply all(3)
小葫芦

Do a recursive search, and then find the one when parent_id=null

仅有的幸福

There are 2 methods you can try:

  1. Query all ids and parent_id, and then search, so that fixed sql statements can be cached.

  2. 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.

漂亮男人
    $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);
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!