Skip to content
Advertisement

How to sum up property string length by ID using PHP in a JSON array

I am trying to sum up the character count(total string length) of all the characters contained in the various “info” properties by “user_id”. I am trying to have a situation where USER-ID A001 has 300 total characters in INFO

I am hoping someone can point me in the right direction.

Below is my code snippet:

{
    "main": {
        "request": "40"
    },
    "data": {
        "page": 1,
        "posts": [
            {
                "id": "1",
                "name": "John Amos",
                "user_id": "A001",
                "info": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam"
            
            },
            {
                "id": "2",
                "name": "Ugon Charles",
                "user_id": "A007",
                "info": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam"
            
            },
            {
                "id": "3",
                "name": "Mary Ann",
                "user_id": "A004",
                "info": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam"
            
            },
            {
                "id": "4",
                "name": "Mary Ann",
                "user_id": "A004",
                "info": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam"
            
            },
            {
                "id": "5",
                "name": "John Amos",
                "user_id": "A001",
                "info": "Sed ut perspiciatis unde omnis iste"
            
            },
            {
                "id": "6",
                "name": "John Amos",
                "user_id": "A001",
                "info": "Ut enim ad minima veniam"
            
            }
            
            
        ]
    }
}

MY PHP

foreach ($data['data']['posts'] as $arr) {
    foreach ($arr->strlen($data['data']['posts']['info']) as $obj) {
        ${$obj->user_id} += $obj->info;
        
    }
}

Advertisement

Answer

Use an associative array to hold the results, with the user_id values as the keys.

$lengths = [];

foreach ($data['data']['posts'] as $post) {
    $userid = $post['user_id'];
    if (isset($lengths[$userid])) {
        $lengths[$userid] += strlen($post['info']);
    } else {
        $legths[$userid] = strlen($post['info']);
    }
}
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement