Home > Blockchain >  PHP - sort string array
PHP - sort string array

Time:10-13

I have a program where I receive a string at the input and store it line by line in the field, for example list [0] = 'Roll 5CZK', etc .. I also have a function that finds the value from the string (number, here 5). How can I sort this field. I don't want to solve it with a 2D array

$string='Rohlík 5Kč
CZK400 Knížka
Pivo 42,-
Houska 4 Kč';
$list = explode(PHP_EOL, $string);

getPrice($list[1]); // => 400
getPrice($list[2]; // => 42

CodePudding user response:

Solution with usort as in the comment, only $a and $b swapped to achieve a descending sort.

$arr = array (
  0 => "Rohlík 5Kč",
  1 => "CZK400 Knížka",
  2 => "Pivo 42,-",
  3 => "Houska 4 Kč",
);

/*
 * This is a greatly simplified implementation of getPrice()
 * to make the code reproducible
 */
function getPrice($str){
  return preg_replace('~[^\d]~u','',$str);
}

//Sorting
usort($arr,function($a,$b){
  return getPrice($b) <=> getPrice($a);
});

// Test Output
var_export($arr);

Output:

array (
  0 => 'CZK400 Knížka',
  1 => 'Pivo 42,-',
  2 => 'Rohlík 5Kč',
  3 => 'Houska 4 Kč',
) 
  • Related