Skip to content
Advertisement

sort & display array with most values first in response (php)

I have the below:

        $myData = array();

        while ($list = oci_fetch_array($stid, OCI_ASSOC)) {
            array_push($myData, $list);
        }
    
        header('Content-Type: application/json');
        // echo json_encode($myData); 
        echo "{"data":" .json_encode($myData). "}"; // contains multiple arrays

In which via a sql query the contents populate a kendo grid table.. problem is first array is used by kendo to create the columns and first outputted array is smaller then most arrays thereafter…

How could I sort my output above to include/output my longest array first so my kendo will get all header data to populate max columns

Advertisement

Answer

To sort by the length of the inner arrays descending, you need to compare the length of the second parameter to the first in your callback; you need to return a positive, negative or zero value dependent on whether the length is greater than, less than or equal to the other. You can do this simply by subtraction. For example:

$myData = array(
    array('key2' => 'value1', 'key3' => 'value1', 'key4' => 'value4'),
    array('key4' => 'value4'),
    array('key1' => 'value1', 'key4' => 'value4'),
    array('key1' => 'value1', 'key2' => 'value1', 'key3' => 'value1', 'key4' => 'value4')
);

usort($myData, function ($a, $b) { return count($b) - count($a); });

print_r($myData);

Output:

Array
(
    [0] => Array
        (
            [key1] => value1
            [key2] => value1
            [key3] => value1
            [key4] => value4
        )
    [1] => Array
        (
            [key2] => value1
            [key3] => value1
            [key4] => value4
        )
    [2] => Array
        (
            [key1] => value1
            [key4] => value4
        )
    [3] => Array
        (
            [key4] => value4
        )
)

Demo on 3v4l.org

Note that rather than create JSON yourself, which can be error-prone, you can generate your desired output by json encoding a new array:

echo json_encode(array('data' => $myData));

Output (for my sample data):

{
    "data": [
        {
            "key1": "value1",
            "key2": "value1",
            "key3": "value1",
            "key4": "value4"
        },
        {
            "key2": "value1",
            "key3": "value1",
            "key4": "value4"
        },
        {
            "key1": "value1",
            "key4": "value4"
        },
        {
            "key4": "value4"
        }
    ]
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement