Skip to content
Advertisement

converting an object to an array in laravel

I’m trying to compare two arrays and use the difference of them to remove data from another array but as I use the resulting array to do a array_diff_key using an array_flip it returns; array_diff_key(): Expected parameter 1 to be an array, object given

$unchecked_cols = array_diff($selected_table_cols,$selected_cols);
        $tem_array = [];                    
        foreach ($selected_table_data as $key => $value) {
            $value =array_diff_key($value, array_flip($unchecked_cols));
            $tem_array[$key] = $value;
        }

this is the code and I’ve tried converting the ‘unchecked cols’ to an array using toArray method but then i get: Call to a member function toArray() on array error. what should i do in a case like this.

Advertisement

Answer

To convert object to array you can add (array) before your object

$unchecked_cols = array_diff($selected_table_cols,$selected_cols);
$tem_array = [];                    
foreach ($selected_table_data as $key => $value) {
     $value =array_diff_key((array)$value, array_flip($unchecked_cols));
     $tem_array[$key] = $value;
}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement