1

I have an array with some values which is being declared on the fly:

// a for loop that finds elements from source
$array[] = array($fruit, $color, $shape, $price);

later i have another for loop which displays the items in the array:

for($j = 0; $j < sizeof($array); $j++) {
    echo $array[$j][0]." ".$array[$j][1]." ".$array[$j][2]." ".$array[$j][3]."
             ".$array[$j][4];
}

I am able to display all the information i want properly, however i want to sort the array before displaying based on the $price. e.g

Orange orange round £.6
Mango yellow oval £.9
Apple red round £.4

I want it in the following form

Apple red round £.4
Orange orange round £.6
Mango yellow oval £.9

Using uasort: Before :

Array ( [0] => Array ( [0] => Orange [1] => red [2] => round [3] => .6) 
        [1] => Array ( [0] => Mango [1] => yellow [2] => oval [3] => .9)
        [2] => Array ( [0] => Apple [1] => red [2] => round [3] => .4));

function provided:

function my_cmp_func($a, $b) {
   if($a[3] == $b[3]){
       return -1*strcmp($a[4], $b[4]); // another column added for comparison
   }
   return -1*strcmp($a[3], $b[3]);     
}

uasort($array, 'my_cmp_func');
print_r($array);
1

5 Answers 5

3

you can do that using a custom comparing function

so you start by using the usort function (if you don't need to keep the indexes) so you will call it like this:

usort($array, 'my_cmp_func');

and define the comparing function as:

function my_cmp_func($a, $b)
{
    return strcmp($a[3], $b[3]);    
}

I defined the function using the strcmp because I don't know if the pound sign is part of the value or you just added it now.. but you can define the function the way you want

Edit: I added the sample here http://codepad.org/DxgFznzE to show that it works; and if you want to reverse the sort order just use this in the function:

return -1*strcmp($a[3], $b[3]);

instead of just the value you get from strcmp

Sign up to request clarification or add additional context in comments.

8 Comments

and if you need to maintain index association you can use a very similar function called uasort (php.net/manual/en/function.uasort.php)
I do need to keep the indexes. Otherwise i will loose the associated values.
@Namit if you are calling uasort just before you display the values I am sure that everything is fine.. if what you see is not what you want it's because you are maintaining the index association (you choose to use uasort and not usort) and with your for statement you display the records in the initial order, not in the updated one.. if you change your for statement to a foreach you should be fine.. check the difference here: codepad.org/nOTCwWdu
@Namit the multiplication using -1 is just a way to reverse the order.. and about using another column.. sure you can.. you can do what you want in that function.. the two parameters will be any two elements from the array so you will have all the fields available.. all you need to do is to return a value lower or grater than zero depending on the rules you want to impose.. look at the example on the man page here php.net/manual/en/function.uasort.php
@Namit that's because strcmp is used to compare the values; I used strcmp because I did not know if you have the pound sign in the value or not; if you only have floats in that field you should compare them as numbers; another option would be to use the strnatcmp function instead of strcmp.. so the comparing function becomes return strnatcmp($a[3], $b[3]); because it uses natural order
|
1

If i was suppose to code this.

I would have made another array. Which would have received the value after sorting.

And then I would have displayed the output. I would suggest the bubble sort would be simple enough for this.

Cheers!

One of the example would be something like this

$numbers = array(1,3,2,5,2);  
$array_size = count($numbers);  
echo "Numbers before sort: ";  
for ( $i = 0; $i < $array_size; $i++ )  
   echo $numbers[$i];  
echo "n";  
for ( $i = 0; $i < $array_size; $i++ )  
{  
   for ($j = 0; $j < $array_size; $j++ )  
   {  
      if ($numbers[$i] < $numbers[$j])  
      {  

     //all the swapping variable here.....
         $temp = $numbers[$i];  
         $numbers[$i] = $numbers[$j];  
         $numbers[$j] = $temp;  
      }  
   }  
}  

echo "Numbers after sort: ";  
for( $i = 0; $i < $array_size; $i++ )  
   echo $numbers[$i];  
echo "n";  

4 Comments

I see what you mean, but lets take my example and apply this case. Once everything is sorted. Wont it mess up the entire table, won't it change the price value of the fruit. I think this will simply sort the price column but will not change the positions of the other columns. I need a way to make price as the key and change the entire row. Hope you understand! :s
Oh, yes I get you. Similar to sort function provided in excel. When you sort something the whole table(values) get sorted along with your key column. Is that what you are referring?
That is exactly what i mean, but would the above method stated by you let me do that?
This one wont, because its a swap of numbers a bit of modification would do. This part if ($numbers[$i] < $numbers[$j]) { $temp = $numbers[$i]; $numbers[$i] = $numbers[$j]; $numbers[$j] = $temp; } Add all the variable and swap them...
0

Store it in an associative array, which will allow you to use the price as the key and easily print the items in ascending key order.

Comments

0

If you're not going to have repeat prices, use the price as the key of the array. Like:

$array[$price] = array($fruit, $color, $shape, $price);

Then sort by keys:

ksort($array);

Then do your output.

If you will have repeat prices, you could probably use array_walk or array_multisort.

Comments

0

Just call array_multisort($array); before your for loop.

array_multisort() can do many useful sorting things - see details here - http://www.php.net/manual/en/function.array-multisort.php

Also, your for loop can be simplified as -

foreach($array as $a) {
    echo $a[0] . " " . $a[1] . " " . $a[2] . " " . $a[3];
}

1 Comment

It performs the sort operation on the first column.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.