thinkphp uses the Model model to manipulate the data and reports an error Indirect modification of overloaded element of XXX has no effect during foreach traversal

1. Example of error report:

1. No error will be reported when directly using the Db class to operate the database. The source code is as follows:

        $data = Config::where('ishide',0)->select();
        $new_data= array();
        foreach($data as $k => $d){
            if($d['pid']==0){
                $new_data[] = $d;
                unset($data[$k]);
            }
        }  
        foreach($new_data as $k => $d){ 
            $new_data[$k]['child'] = array();
            foreach($data as $kk => $dd){
                if($d['id'] == $dd['pid']){
                    $new_data[$k]['child'][]=$dd;
                    unset($data[$kk]);
                }
            } 
        }

2. When using Model operation, $new_data[$k]['child'][]=$dd; This line of code will report an error, and the error message is as follows:

        $data = Config::where('ishide',0)->select();
        $new_data= array();
        foreach($data as $k => $d){
            if($d['pid']==0){
                $new_data[] = $d;
                unset($data[$k]);
            }
        }  
        foreach($new_data as $k => $d){ 
            $new_data[$k]['child'] = array();
            foreach($data as $kk => $dd){
                if($d['id'] == $dd['pid']){
                    $new_data[$k]['child'][]=$dd;
                    unset($data[$kk]);
                }
            } 
        }

 2. Error analysis:

1. When Thinkphp uses the Db class to operate data query, the default data type returned is: array , so it is no problem to use foreach to traverse and modify directly.

2. When we use the Model model class to manipulate the data query, the returned data type is: object , the object cannot be modified by foreach traversal, so the error "indirect modification of the overloaded element of XXX has no effect" will be reported .

Solution: 

1. Add the following code to the Model class:

//设置返回数据结果类型
protected $resultSetType = 'collection';

2. After querying the result, use the toArray() method to convert the object into an array, as follows:

$data = Config::where('ishide',0)->select()->toArray();

 

 

Guess you like

Origin blog.csdn.net/qq15577969/article/details/113824450