i have following data as an associative array
array
'abc' =>
array
'label' => string 'abc' (length=3)
'weight' => float 3
'wsx' =>
array
'label' => string 'wsx' (length=3)
'weight' => float 1
'qay' =>
array
'label' => string 'qay' (length=3)
'weight' => float 1
'http://test.com' =>
array
'label' => string 'http://test.com' (length=15)
'weight' => float 0
'Nasi1' =>
array
'label' => string 'Nasi1' (length=5)
'weight' => float 0
'fax' =>
array
'label' => string 'fax' (length=3)
'weight' => float 4
I want to sort the array using "label" or "weight"
The compare function for the label is:
function compare_label($a, $b)
{
return strnatcmp($a['label'], $b['label']);
}
and than i just call the function from another function:
usort($label, 'compare_label');
var_dump($label);
but then i get the error message and the array is not sorted. I don't know, what I'm doing wrong. I've tried to replace:
usort($label, 'compare_label');
with usort($label, compare_label);
usort($label, 'compare_label');
with usort($label, $this->compare_label);
without success. Can someone give me a hint?
if compare_label
is a member function (i.e., class method) then you need to pass it differently.
usort( $label, array( $this, 'compare_label' ) );
Basically, instead of just sending a string of the function name, you send an two-element array, where the first element is the context (object on which the method can be found), and the 2nd element is the string of the function name.
NOTE: If your method is static, then you pass the class name as the first element of the array
usort( $label, array( __CLASS__, 'compare_label' ) );
Is the compare function defined as a global function or as a method of an object? If it's a method, you'll have to change how you call it slightly:
usort($label, array($object, "compare_label"));
You can also declare it as a static method of the class itself:
public static function compare_label ($a, $b) {
[...]
}
usort($label, array(Class_Name, "compare_label"));
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