Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

usort function in a class

Tags:

php

I have a function which sorts data in a multidimensional array, as shown below:

<?php   $data = array();   $data[] = array("name" => "James");   $data[] = array("name" => "andrew");   $data[] = array("name" => "Fred");    function cmp($a, $b)   {       return strcasecmp($a["name"], $b["name"]);   }    usort($data, "cmp");    var_dump($data);   ?>   

When i run this, it works as expected, returning the data ordered by name, ascending. However, I need to use this in a class.

<?php class myClass   {       function getData()       {           // gets all data         $this -> changeOrder($data);     }        function changeOrder(&$data)       {            usort($data, "order_new");     }      function order_new($a, $b)       {           return strcasecmp($a["name"], $b["name"]);       } } ?> 

When I use this, i get the following warning: Warning: usort() expects parameter 2 to be a valid callback, function 'order_new' not found or invalid function name.

When i put the order_new function in the changeOrder function it works fine, but I have problems with Fatal error: Cannot redeclare order_new(), so i cannot use that. Any suggestions?

like image 543
Marinus Avatar asked Jul 03 '12 14:07

Marinus


People also ask

How does usort work PHP?

The usort() function in PHP sorts a given array by using a user-defined comparison function. This function is useful in case if we want to sort the array in a new manner. This function assigns new integral keys starting from zero to the elements present in the array and the old keys are lost.

How to sort array of object in PHP?

Approach: The usort() function is an inbuilt function in PHP which is used to sort the array of elements conditionally with a given comparator function. The usort() function can also be used to sort an array of objects by object field.

Is PHP Usort stable?

Sorting functions in PHP are currently unstable, which means that the order of “equal” elements is not guaranteed.

How do you Unsort an array in PHP?

PHP usort() Function $a=array(4,2,8,6); usort($a,"my_sort");


2 Answers

order_new is a class method not a global function. As the PHP-Manual suggest you can use in this case

usort($data, array($this, "order_new"));  

or declare order_new static and use

usort($data, array("myClass", "order_new"));  
like image 93
worenga Avatar answered Oct 10 '22 02:10

worenga


Change to usort($data, array($this, "order_new"));

like image 32
xdazz Avatar answered Oct 10 '22 02:10

xdazz