Re: Multidimensional array help
| From: | Marek Kilimajer | Date: | Mon, 21 Oct 2002 17:26:55 +0000 |
| Subject: | Re: Multidimensional array help | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-120770@lists.php.net to get a copy of this message | ||
The foreach loop is useless, as one of the conditions will be met nad your functions returns.
I'm not sure, if you know you now have $foo contain
$foo[0][0], $foo[1][0], $foo[1][1], $foo[1][2], $foo[2][0], and this makes it inconsistent,
there is one in $foo[0] and 3 in $foo[1].
Maybe you want
function cmp ($a, $b)
{
if ($a[$k]['rank'] < $b[$k]['rank']) return 1;
if ($a[$k]['rank'] > $b[$k]['rank']) return -1;
if ($a[$k]['rank'] == $b[$k]['rank']) return 0;
}
foreach($a as $k => $null)
{
uasort ($foo[$k], 'cmp');
}
Gerard Samuel wrote:
Hi all. Im trying to sort a multidimensional array using uasort().
I haven't used it before, so Im not too sure on its usage.
Here is what I have ->
--------------------
<?php
echo header('Content-type: text/plain');
$foo[0][] = array('title' => 'Title 1', 'summary' => 'Summary 1', 'rank' => 13);
$foo[1][] = array('title' => 'Title 2', 'summary' => 'Summary 2', 'rank' => 7);
$foo[1][] = array('title' => 'Title 3', 'summary' => 'Summary 3', 'rank' => 3);
$foo[2][] = array('title' => 'Title 4', 'summary' => 'Summary 4', 'rank' => 11);
$foo[1][] = array('title' => 'Title 9', 'summary' => 'Summary 9', 'rank' => 4);
function cmp ($a, $b)
{
foreach($a as $k => $null)
{
if ($a[$k]['rank'] < $b[$k]['rank']) return 1;
if ($a[$k]['rank'] > $b[$k]['rank']) return -1;
if ($a[$k]['rank'] == $b[$k]['rank']) return 0;
}
}
uasort ($foo, 'cmp');
print_r($foo);
?>
----------------------
Im trying to sort the array in descending order by the rank's value.
Im not sure if Im heading in the right direction with this, but any help would be appreciated.
Thanks.