1

I have this multi value array which I want to sort

Array(
    [0] => word1 131
    [1] => word2 3
    [2] => word3 5
    [3] => word4 4
    [4] => word5 16
    [5] => word6 29
)

How do I sort it using the number value on the right so the result will be like this.

Array(
    [0] => word2 3
    [1] => word4 4
    [2] => word3 5
    [3] => word5 16
    [4] => word6 29
    [5] => word1 131
)

Thx

4 Answers 4

3

You'll want to use usort and create a callback function that parses the string and sorts the data.

function usort_callback($a, $b)
{
  $a = preg_replace('/^.+\s(\d+)$/', '$1', $a);
  $b = preg_replace('/^.+\s(\d+)$/', '$1', $b);

  return ( intval($a) < intval($b) ) ? -1 : 1;
}

usort($array, 'usort_callback');
Sign up to request clarification or add additional context in comments.

1 Comment

This is working great man! Thank you very much! I just wasted hours without knowing usort function lol
0

You will need to use explode or str_split() to isolate the number on the right, sort using array_sort() or one of the related functions, and reassemble the array.

Comments

0

Define a comparison function and use usort. In your comparison function you can use str_split or pregmatch to get interesting parts of strings.

Comments

0

You can use usort and users function like this:

<?php
function cmp($a, $b) {
    $a = (int)substr(strstr($a, ' '), 1); 
    $b = (int)substr(strstr($b, ' '), 1);   
    return ($a < $b) ? -1 : 1;
}

$array = array(
    'word1 131',
    'word2 3',
    'word3 5',
    'word4 4',
    'word5 16',
    'word6 29'
);

usort($array, "cmp");

foreach ($array as $key => $value) {
    echo "$key: $value\n";
}
?>

1 Comment

this is great too with invoking regex engine! thanks. Sorry can't vote up yet :(

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.