Link to home
Start Free TrialLog in
Avatar of Lupi05
Lupi05

asked on

Need regex for PHP sort function

Hi,

in PHP, I need to sort a twodimensional array $filteredresults:

The function compare that I attached below works and I'm using it.
The problem is that I am sorting the array by field [3] which is a price (currency EURO ¬).

The prices look like
¬ 20,99
¬ 10,50
¬ 132,20

When the array is created this is what I used for field [3]
"€ " . number_format($price, 2, ',', '');

So this means the EURO currency symbol (€) followed by one whitespace, then the price, using a comma as decimal point and no seperator for thousands.

Thus, I need a regex which strips everything but the digits and replaces the decimal comma with a decimal point to do proper sorting.

I'd prefer it if the change wasn't permanent, for instance if we could just add something to the compare function below.

for instance:
if ($x[3].regex(blabla)) == $y[3].regex(blabla)) {return 0;}

Thanks for your help.
Cheers, Chris

function compare($x, $y) {
     if ($x[3] == $y[3]) {return 0;}   
     else if ($x[3] < $y[3])
	return -1;
     else
        return 1;
}
 
usort($filteredresults, "compare");

Open in new window

Avatar of ddrudik
ddrudik
Flag of United States of America image

Lupi05, it might help those of us considering the question if you include real-world content, please output your array using var_dump or print_r.  Thanks.
Avatar of Lupi05
Lupi05

ASKER

Hi, sorry that I didn't post the print_r yet... Here you go:

Sort by field [3].

Array ( [0] => Array ( [0] => SomeMerchant [1] => 2 x 10 [2] => ¬ 21,80 [3] => ¬ 0,81 [4] => ¬ 5,00 [5] => ¬ 48,60 ) [1] => Array ( [0] => SomeMerchant [1] => 2 x 10 [2] => ¬ 23,95 [3] => ¬ 0,83 [4] => ¬ 1,60 [5] => ¬ 49,50 ) [2] => Array ( [0] => SomeMerchant [1] => 2 x 10 [2] => ¬ 24,90 [3] => ¬ 0,90 [4] => ¬ 3,90
(frei ab ¬ 59,00) [5] => ¬ 53,70 ) [3] => Array ( [0] => SomeMerchant [1] => 2 x 10 [2] => ¬ 26,00 [3] => ¬ 0,94 [4] => ¬ 4,50
(frei ab ¬ 69,00) [5] => ¬ 56,49 ) [4] => Array ( [0] => SomeMerchant [1] => 2 x 10 [2] => ¬ 48,90 [3] => ¬ 0,57 [4] => ¬ 5,00 [5] => ¬ 102,80 ) [5] => Array ( [0] => SomeMerchant [1] => 2 x 10 [2] => ¬ 63,98 [3] => ¬ 0,72 [4] => ¬ 1,60 [5] => ¬ 129,55 ) [6] => Array ( [0] => SomeMerchant [1] => 2 x 10 [2] => ¬ 68,40 [3] => ¬ 0,76 [4] => frei [5] => ¬ 136,80 ) [7] => Array ( [0] => SomeMerchant [1] => 2 x 10 [2] => ¬ 72,50 [3] => ¬ 0,81 [4] => frei [5] => ¬ 144,99 ) )

Cheers, Chris
ASKER CERTIFIED SOLUTION
Avatar of Lupi05
Lupi05

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial