Sorting an array in php

matthew1471

New member
May 13, 2007
242
0
0
Bournemouth, UK.
How would you sort an array of these values so that they're in ascending price order?

I've been trying with sort() and natsort() and suchlike but with no joy.

32 inch lcd tv and £5 cashback
32 inch lcd tv and £50 cashback
32 inch lcd tv and £55 cashback
32 inch lcd tv and £45 cashback
32 inch lcd tv and £40 cashback
32 inch lcd tv and £30 cashback
32 inch lcd tv and £35 cashback
32 inch lcd tv and £60 cashback
32 inch lcd tv and £65 cashback
32 inch lcd tv and £90 cashback
32 inch lcd tv and £95 cashback
32 inch lcd tv and £85 cashback
32 inch lcd tv and £80 cashback
32 inch lcd tv and £70 cashback
32 inch lcd tv and £75 cashback
32 inch lcd tv and £25 cashback
32 inch lcd tv and £20 cashback
32 inch lcd tv and £115 cashback
32 inch lcd tv and £120 cashback
32 inch lcd tv and £125 cashback
32 inch lcd tv and £110 cashback
32 inch lcd tv and £105 cashback
32 inch lcd tv and £10 cashback
32 inch lcd tv and £100 cashback
32 inch lcd tv and £130 cashback
32 inch lcd tv and £135 cashback
32 inch lcd tv and £155 cashback
32 inch lcd tv and £160 cashback
32 inch lcd tv and £150 cashback
32 inch lcd tv and £15 cashback
32 inch lcd tv and £140 cashback
32 inch lcd tv and £145 cashback
32 inch lcd tv
 


SELECT * FROM `table` ORDER BY `price` ASC;

assuming he doesn't have each one of those lines in a "title" column without price as it's own column...

You could brute force it and regex out the prices and put the whole thing in a hash array, then sort by the keys (prices).

Probably isn't the most scalable, but that would work for small amounts of data.
 
You have an array of String and you are sorting by ASCII value not by integer value, that's the reason you get odd results.
Use a REGEX function to isolate the value after char £ and use this value as index of your sorting method.
 
I had thought from the start that I may end up pulling each value apart and re-ordering it.

Anyway, here it is.

Thanks for the advice guys.


PHP:
function reOrder($arrayName)
{
        $pattern = "/and (.*) cash/";

        $reOrder = array();
        foreach ($arrayName as $arrayNameLoop)
        {
                preg_match($pattern, $arrayNameLoop, $matches);
                $reOrder[$matches['1']] = $arrayNameLoop;
        }
        ksort($reOrder);
        return $reOrder;
}


$string = array('28 tv and 20 cash','28 tv and 5 cash','28 tv and 10 cash','28 tv and 90 cash', '28 tv and 120 cash','28 tv and 30 cash','28 tv and 70 cash','28 tv and 15 cash');

$reOrdered = reOrder($string);

foreach ($reOrdered as $id => $item)
{
        print $id." / ".$item."<br/>";
}