0

I have an array of objects like below:

[
    {
        "TYPE": "food",
        "NAME": "abc"
    },
    {
        "TYPE": "fruit",
        "NAME": "xyz"
    },
    {
        "TYPE": "food",
        "NAME": "def"
    },
    {
        "TYPE": "food",
        "NAME": "ghi"
    },
]

How can I split this array of objects into multiple arrays such that the desired output looks like:

[
    {
        "TYPE": "food",
        "ITEMS": 
        [
            {
                "TYPE": "food",
                "NAME": "abc"
            },
            {
                "TYPE": "food",
                "NAME": "def"
            },
            {
                "TYPE": "food",
                "NAME": "ghi"
            },
        ]
    },
    {
        "TYPE": "fruit",
        "ITEMS": 
        [
            {
                "TYPE": "fruit",
                "NAME": "xyz"
            },
        ]
    },
]

Note that the parent object has its own identifier (TYPE)

I tried this:

    $result = [];
    foreach ($DT_DATA as $key => $value) {
        $group = $value->TYPE;
        if (!isset($result[$group])) {
            $result[$group] = [];
        }

        $result[$group][] = $value;
    }
    $result = array_values($result);

But the parent group does not contain "TYPE" and also "ITEMS" array

1 Answer 1

2

Some improvements that will do the job:

$result = [];
foreach ($DT_DATA as $key => $value) {
    $group = $value->TYPE;
    if (!isset($result[$group])) {
        // init with array of required structure
        $result[$group] = [
            'TYPE' => $group,
            'ITEMS' => [],
        ];
    }

    // add $value to `ITEMS` subarray
    $result[$group]['ITEMS'][] = $value;
}
$result = array_values($result);
Sign up to request clarification or add additional context in comments.

2 Comments

Any idea how I can split into a third level with a different key? say, the third key 'COLOR'. Meaning it would be TYPE > COLOR > {TYPE: "FRUIT", NAME: "xyz", COLOR: "RED"}
Add to ITEMS under key COLOR? But it's better to ask new question with related data provided.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.