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;
}
}
CodePudding user response:
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']);
}
}
CodePudding user response:
As I understood what you want is to get the total count of each post "info" length (or total characters) and the general total count of all those.
$data = json_decode($a,true);
$total = 0;
foreach ($data['data']['posts'] as $key => $arr) {
$data['data']['posts'][$key]['count'] = strlen($arr['info']);
$total = strlen($arr['info']);
}
$data['data']['total_count'] = $total;
echo 'total count is '.$data['data']['total_count'].PHP_EOL;
this outputs: total count is 647