-1

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.

3

2 Answers 2

2
$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);
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.