0

If I run this :

echo '<pre>';print_r($a);echo '</pre>';

The result :

Array ( [0] => stdClass Object ( [id] => 3 [name] => chelsea.png ) [1] => stdClass Object ( [id] => 4 [name] => arsenal.png ) [2] => stdClass Object ( [id] => 5 [name] => mu.png ) )

If I run this :

echo '<pre>';print_r($b);echo '</pre>';

The result :

Array ( [0] => Array ( [id] => 1 [name] => city.png ) )

Then I merge use :

$c = array_merge($a, $b);

echo '<pre>';print_r($c);echo '</pre>';

The result :

Array ( [0] => stdClass Object ( [id] => 3 [name] => chelsea.png ) [1] => stdClass Object ( [id] => 4 [name] => arsenal.png ) [2] => stdClass Object ( [id] => 5 [name] => mu.png ) [3] => Array ( [id] => 1 [name] => city.png ) )

I want to sort the array by id

I try this :

ksort($c);

Then I run

echo '<pre>';print_r($c);echo '</pre>';

The result :

Array ( [0] => stdClass Object ( [id] => 3 [name] => chelsea.png ) [1] => stdClass Object ( [id] => 4 [name] => arsenal.png ) [2] => stdClass Object ( [id] => 5 [name] => mu.png ) [3] => Array ( [id] => 1 [name] => city.png ) )

It does not work. Position id = 1 has a position at the very end. It should be in the first position

How can I solve it?

moses toh
  • 12,344
  • 71
  • 243
  • 443
  • 1
    https://stackoverflow.com/questions/20230926/is-there-a-way-to-choose-the-sorting-of-ksort-like-asc-desc check it – RohitS Jun 18 '17 at 06:45
  • @RohitS, Do not you read my question? I already use `ksort` – moses toh Jun 18 '17 at 06:47
  • ksort does work (on it's own), it just does not work in your case, or better worded: you use the wrong function for the sort operation you'd like to do. - Please see existing Q&A resources about the general problem - like the one linked as duplicate - before posting another question. Otherwise future users will have more and more problems to locate a good solution for them fast. – hakre Jun 18 '17 at 06:49
  • 2
    Possible duplicate of: https://stackoverflow.com/questions/2286597/using-usort-in-php-to-sort-an-array-of-objects – mickmackusa Jun 18 '17 at 07:05
  • @TrendingNews not sure did you read the linked answer?? did someone said you didnt used something? – RohitS Jun 18 '17 at 07:15
  • @TrendingNews Your `$a` is an array of objects, but `$b` is an array of array. So you have to trans then into the same structure as array of array, or array of objects, or not trans them but with a complex compare function in the next sort process. As @mickmackusa's comment, then you can use usort to sort it. – LF00 Jun 18 '17 at 07:39

0 Answers0