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?
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.
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.
Sorting functions in PHP are currently unstable, which means that the order of “equal” elements is not guaranteed.
PHP usort() Function $a=array(4,2,8,6); usort($a,"my_sort");
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"));
Change to usort($data, array($this, "order_new"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With