phparrayssortingdelimitedcustom-sort

Sort array of strings based on priority substring at the end of the string


How can I order an array from this:

$unordered_array = ['11196311|3','17699636|13','11196111|0','156875|2','17699679|6','11196237|7','3464760|10'];

To this

$ordered_array = ['11196111', '156875', '11196311', '17699679','11196237','3464760', '17699636'];

The number after the "|" defines the position, and the array needs to be ordered from lower to higher, and remove the position number in the final array.


Solution

  • $array = array();
    foreach($unordered_array as $value) {
        $value = explode('|', $value);
        $array [$value[1]]= $value[0];    
    }
    ksort($array);
    $ordered_array = array_values($array);
    
    var_dump($ordered_array);