Skip to content
Advertisement

Sort Array from object

I have an object and store it in an array. However, when outputting the names from the object, I want to sort them by ‘is_main’. Thereby ‘is_main’ with the value 1 should always be in the first place and then ‘is_main’ with the value 0. Here is the Object

JavaScript

And my PHP Code:

JavaScript

I hope that someone can help me by this problem.

Advertisement

Answer

You can use usort with a callback defining what you’re looking for in the sort function.

JavaScript

If the value is_main is set and is true(equals 1), it will go to the top of the array and once you echo out your storage variable, you will see all of the is_main teachers at the top.

Check out this documentation for callback sorting of arrays.

https://www.php.net/manual/en/function.usort.php

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement