Numbered_props_to_array

The numbered_props_to_array function can be used to create an array of objects, based on the key names of the input object. Practically, by evaluating the names of the keys, the keys are grouped into objects, which are then enclosed within an array.

Syntax

array numbered_props_to_array(json_object $object)

Results in a new array of objects based on the properties from the JSON $object, where the name of each key-value pair is considered to have an explicit (or implicit) ordering representation that defines its resulting position in the array.

This index order of each key is taken from its name’s suffix, which is considered 0 when absent. For example, a key named “first_name” will be in the first object of the array (index = 0), while a key named “first_name9” will have “9” as its index number.

Parameters

$object: A JSON object, the keys of which will be evaluated and used to generate an array of objects.

Example

In the sample data below, an object that has two kinds of keys is used. More specifically, it features keys that are either named “name” or “location” (and hold relevant data).

{
  "info": {
    "name": "John",
    "location": "Gainsville, Florida, USA",
    "name2": "Rasmus",
    "location2": "Helsingør, DK",
    "name3": "Jean",
    "name4": "Laura",
    "location4": "London, UK",
    "location5": "Madrid, ESP",
    "location3": "Lyon, FR",
    "name6": "Maria"
  }
}
{
    info_grouped: numbered_props_to_array(info)
}

Below is the result of the transformation. It can be noticed that the “name” and “location” keys that had the same order number in their name were matched together regardless of whether or not they were placed right after each other in the original object. Furthermore, keys that didn’t have a pair were still placed into their own object while maintaining the same ordering (fx. “location5” and “name6”).

{
  "info_grouped": [
    {
      "name": "John",
      "location": "Gainsville, Florida, USA"
    },
    {
      "name": "Rasmus",
      "location": "Helsingør, DK"
    },
    {
      "name": "Jean",
      "location": "Lyon, FR"
    },
    {
      "name": "Laura",
      "location": "London, UK"
    },
    {
      "location": "Madrid, ESP"
    },
    {
      "name": "Maria"
    }
  ]
}

Lastly, it is worth mentioning, that the numbered_props_to_array function renames the keys so that each object of the generated array has the same keys. For example “name2” in the sample data was renamed to just “name” in the second object of the generated array.