Array to string conversion error when sorting array - Printable Version +- CodeIgniter Forums (https://forum.codeigniter.com) +-- Forum: Using CodeIgniter (https://forum.codeigniter.com/forumdisplay.php?fid=5) +--- Forum: General Help (https://forum.codeigniter.com/forumdisplay.php?fid=24) +--- Thread: Array to string conversion error when sorting array (/showthread.php?tid=78000) |
Array to string conversion error when sorting array - IvanBell - 11-17-2020 Hello! Suppose I have a database with a column called "weight" and I have this function in my model: Code: public function test() Then I call this function in my controller: Code: $model = new MyModel(); Then I put the $test variable inside $data and pass it to my view file. Now in the view file I print the array: Code: <?php print_r($test); ?> Here is the result I get: Array ( [0] => Array ( [weight] => 90 kg ) [1] => Array ( [weight] => 92 kg ) [2] => Array ( [weight] => 100 kg ) [3] => Array ( [weight] => 94 kg ) [4] => Array ( [weight] => 98 kg ) [5] => Array ( [weight] => 125 kg ) ) If I try to sort $test using asort($test), it works. But if I use natsort($test), I get error "Array to string conversion." The same happens if I use array_multisort($test, SORT_NATURAL) or sort($test, SORT_NATURAL). I have no idea why it happens. Could you please help me? RE: Array to string conversion error when sorting array - schertt - 11-17-2020 You're trying to sort the values of $test as if they are alphanumeric strings (this is what "natural ordering" is) but the aren't strings, they're Arrays. Take another look at it: PHP Code: $test = [ Anything that attempts to sort this by natural order is going to fail because you can't convert an Array to a string. This is why your the last three commands fail. I also suspect that asort isn't actually working as you intended either. PHP Code: php > $test = [ Here's a hint that might get you started in the right direction: PHP Code: php > foreach ($test as $k=>&$v){$v = $v['weight'];} RE: Array to string conversion error when sorting array - muuucho - 11-18-2020 Or use array_column RE: Array to string conversion error when sorting array - IvanBell - 11-18-2020 Thanks a lot! I have easily solved my problem with your help |