0

I want to sort the values by ascending order.

I tried ksort, and other sorting examples.

Array
(
    [0] => stdClass Object
        (
            [tenure] => 1 year to less than 2 years
        )

    [1] => stdClass Object
        (
            [tenure] => 10 years to less than 15 years
        )

    [2] => stdClass Object
        (
            [tenure] => 15 years or more
        )

    [3] => stdClass Object
        (
            [tenure] => 2 years to less than 5 years
        )

    [4] => stdClass Object
        (
            [tenure] => 5 years to less than 10 years
        )

)

I want to sort the tenure values of the above array.

3 Answers 3

2

You can use core array_multisort

array_multisort(array_column($array, 'tenure'),   
SORT_ASC, SORT_NATURAL, $array);

https://3v4l.org/cXNQH.

Sign up to request clarification or add additional context in comments.

1 Comment

This is good. I forget that array_column works on arrays of objects too.
2

Since your values all start with numbers, you can convert them to integers and sort on those using usort:

usort($array, function ($a, $b) { return (int)$a->tenure - (int)$b->tenure; });
print_r($array);

Output:

Array (
  [0] => stdClass Object (
    [tenure] => 1 year to less than 2 years
  )
  [1] => stdClass Object (
    [tenure] => 2 years to less than 5 years
  )
  [2] => stdClass Object (
    [tenure] => 5 years to less than 10 years
  )
  [3] => stdClass Object (
    [tenure] => 10 years to less than 15 years
  )
  [4] => stdClass Object (
    [tenure] => 15 years or more
  )
)

Demo on 3v4l.org

Comments

1

You can use array_walk, ksort, You can change object to array using

$arr = (array) $object;

after that try this

$res=[];
array_walk($arr, function($v, $k) use (&$res){
  $key = substr($v['tenure'], 0, strspn($v['tenure'], "0123456789"));
  $res[$key] = $v;
});
ksort($res);

Working Demo

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.