Ángel Yarmas
Ángel Yarmas

Reputation: 1

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.

Upvotes: -1

Views: 48

Answers (2)

mickmackusa
mickmackusa

Reputation: 47864

Split the values into two arrays containing the ids and the ordering priorities, then sort the ids array using the priorities array. The following approach will even work when the same priority number is assigned to more than one id.

Code: (Demo)

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

$ids = [];
$priorities = [];
foreach ($unordered_array as $v) {
    [$ids[], $priorities[]] = explode('|', $v);
}
array_multisort($priorities, SORT_NUMERIC, $ids);
var_export($ids);

Upvotes: 1

Vincent Decaux
Vincent Decaux

Reputation: 10714

$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);

Upvotes: 2

Related Questions