kishan
kishan

Reputation: 13

Customizing Array

I had a Response coming like a JSON array like below and I need to sort out the JSON containing the same roleId and TenantId and send them with all the features in the same array.

[
    {
        "roleId": 1,
        "role": "admin",
        "featureId": 1,
        "feature": "Dashboard",
        "tenantId": 1,
        "tenant": "Admin"
    },
    {
        "roleId": 1,
        "role": "admin",
        "featureId": 2,
        "feature": "Overview",
        "tenantId": 1,
        "tenant": "Admin"
    },
    {
        "roleId": 1,
        "role": "admin",
        "featureId": 3,
        "feature": "Devices",
        "tenantId": 1,
        "tenant": "Admin"
    },
    {
        "roleId": 1,
        "role": "admin",
        "featureId": 4,
        "feature": "Map View",
        "tenantId": 1,
        "tenant": "Admin"
    }
]

I need to customize it and return as a response like below grouping by tenantid and role in a sub json

{
    "roleId": 1,
    "role": "admin",
    "features": [
        {
            "featureId": 1,
            "feature": "Dashboard"
        },
        {
            "featureId": 2,
            "feature": "Overview",
        },
        {
            "featureId": 4,
            "feature": "Map View",
        },
        {
            "featureId": 3,
            "feature": "Devices",
        }
    ],
    "tenantId": 1,
    "tenant": "Admin"
},
{
    "roleId": 2,
    "role": "monitor",
    "features": [
        {
            "featureId": 1,
            "feature": "Dashboard"
        },
        {
            "featureId": 2,
            "feature": "Overview",
        },
        {
            "featureId": 4,
            "feature": "Map View",
        },
        {
            "featureId": 3,
            "feature": "Devices",
        }
    ],
    "tenantId": 1,
    "tenant": "Admin"
}

Expected UI should be something like below after integration

UI Image

Please help me out in this

Thanks in advance

Upvotes: 1

Views: 67

Answers (1)

Death-is-the-real-truth
Death-is-the-real-truth

Reputation: 72269

1.You need to decode your json data using json_decode()

2.Then you need to use foreach() to loop this data

3.Now create a new array and assign values to this array inside loop by making roleId as array keys[so that same roleId values will goes to same child-array automatically]

4.Now do array_values() to re-index the final array

5.Encode this using json_encode() to get desired format.

Code:-

$array = json_decode( $json , true);

$final_array = array();

foreach($array as $arr){
    $final_array[$arr['roleId']]['roleId'] = $arr['roleId'];
    $final_array[$arr['roleId']]['role'] = $arr['role'];
    $final_array[$arr['roleId']]['feature'][] = array('featureId'=>$arr['featureId'],'feature'=>$arr['feature']);
}

$final_array = array_values($final_array);
echo json_encode($final_array);

Output:-https://3v4l.org/CuCI2

Upvotes: 1

Related Questions