usort overwriting head or tail of array?
I don't fully understand how PHP allocates, so I don't know if I have made an error, or if this is a bug.
usort() here is intermittently zeroing out the head or tail of the array.
class foo
{
开发者_运维问答 public $idx;
public $data;
}
function compare_foos ($a, $b)
{
if ($a->data == $b->data)
return 0;
elseif ($a->data < $b->data)
return -1;
else
return 1;
}
$mylist = Array ();
for ($i=0; $i < 10; ++$i)
{
$mylist[$i] = new foo ();
$mylist[$i]->idx = $i;
$mylist[$i]->data = rand() % 20;
}
print_r ($mylist);
usort ($mylist, compare_foos);
echo "<HR>";
print_r ($mylist);
Callbacks, like the one used by usort, can be specified in 3 different ways:
a string containing the name of the function:
usort($mylist, 'compare_foos');
an actual function:
usort($mylist, create_function(/*...*/)); // php >= 5.3 only: usort($mylist, function ($a, $b) { /* ... */ });
an array to access object methods:
usort($mylist, array($myobject, 'mymethod'));
Using a callback the way you did is not valid and php returns an error:
PHP Notice: Use of undefined constant compare_foos - assumed 'compare_foos' in /home/lepidosteus/test.php on line 28
To see it, remember to code with every error enabled on your development machine (but hide them on the production server), using error_reporting():
error_reporting(E_ALL); // display all errors including notices
error_reporting(0); // hide all errors
By the way if you want to use an object as a simple store, you don't need to create a dedicated class you can use stdClass():
$mylist[$i] = new stdClass();
$mylist[$i]->idx = $i;
$mylist[$i]->data = rand() % 20;
Also, you can use var_dump() instead of print_r when you debug to get detailed information about the type of each variable, can help you quickly find out if something is wrong.
精彩评论