I have a JSON returned from the backend service.
$a='{
"post_id": [
"1",
"34",
"29",
"35",
"28",
"37"
],
"posted_by": [
"1",
"1",
"1",
"1",
"1",
"3"
],
"total_likes": [
4,
1,
1,
1,
1,
1
]
}';
JSON has post_id, posted_by and how many likes a post received. I convert it into array for processing in php
$data = json_decode($a);
My array looks like this:
stdClass Object
(
[post_id] => Array
(
[0] => 1
[1] => 34
[2] => 29
[3] => 35
[4] => 28
[5] => 37
)
[posted_by] => Array
(
[0] => 1
[1] => 1
[2] => 1
[3] => 1
[4] => 1
[5] => 3
)
[total_likes] => Array
(
[0] => 4
[1] => 1
[2] => 1
[3] => 1
[4] => 1
[5] => 1
)
)
posted_by
is user. and what I'm trying to do is to find how many likes a user received and save that value in a new array. SO, in this case, user 1 received 8 likes and user 3 received 1 like. And,I have to save this in an array.
So, for achieving that, I tried something like this but I didn't get any results. Undefined offset error is shown when the loop executes for the nth time.
$total_likes=0;
$data2=array();
for($j=0; $j<sizeof($data['posted_by']);$j++)
{
if($data['posted_by'][$j] == $data['posted_by'][$j+1])
{
$data2[$j]['user'] = $data['posted_by'][$j];
$data2[$j]['likes'] = $total_likes + $data['total_likes'][$j];
}
}
Is there any built in function to do such a check?