Home > Blockchain >  In PHP, is there an easy way to sort arbitrarily nested json data by KEY?
In PHP, is there an easy way to sort arbitrarily nested json data by KEY?

Time:08-19

I want to be able to sort an arbitrarily nested json object by its KEY values using PHP. The json data may have arrays, in which case I'd still want to sort values by keys if they existed, otherwise, by the string values. Is there an easy way of doing this already? I've looked at usort, but it seems to be unable to do what I am trying to accomplish.

For example, this object (please excuse any malformatted json, I wrote this json by hand in the stack overflow window):

{ 
"state" : "Texas", 
"lastName" : "Straight", 
"all" :
    {
     "my" : "exes",
     "live" : "in"
    },
"firstName":"George",
"hats": 
    [
       "performing": 
          { 
           "quality":"fine",
           "color":"yellow"
          },
       "recreation" :
          {
           "quality" : "worn",
           "color" : "brown"
          }
    ]
}

Would become this object:

{ 
  "all" :
    {
     "live" : "in"
     "my" : "exes"
    },
  "firstName":"George",
  "hats": 
     [
       "performing": 
         { 
          "color":"yellow",
          "quality":"fine"
         },
       "recreation" :
         {
          "color" : "brown",
          "quality" : "worn"
         }
     ],
  "lastName" : "Straight", 
}

With all the values having been sorted by key.

I understand that I could build something over the course of some hours to recursively sort through the objects and arrays, but I'm just looking to see if there is already a solution out there, as I feel like I can't have been the only person to ever have wanted to do this in PHP.

Any help would be very appreciated.

CodePudding user response:

Assuming the JSON string was decoded as an associative array, you can sort it recursively:

<?php

$data = json_decode('
{ 
    "state" : "Texas", 
    "lastName" : "Straight", 
    "all":
    {
        "my" : "exes",
        "live" : "in"
    },
    "firstName": "George",
    "hats": 
    {
        "performing": 
        { 
            "quality":"fine",
            "color":"yellow"
        },
        "recreation" :
        {
            "quality" : "worn",
            "color" : "brown"
        }
    }
}', true);

function ksort_recursive(&$data)
{
    if (!is_array($data)) {
        return;
    }
    ksort($data);
    foreach ($data as &$value) {
        ksort_recursive($value);
    }
}

ksort_recursive($data);
echo json_encode($data, JSON_PRETTY_PRINT);

The output is:

{
    "all": {
        "live": "in",
        "my": "exes"
    },
    "firstName": "George",
    "hats": {
        "performing": {
            "color": "yellow",
            "quality": "fine"
        },
        "recreation": {
            "color": "brown",
            "quality": "worn"
        }
    },
    "lastName": "Straight",
    "state": "Texas"
}
  • Related