I am relatively new at PHP, I am trying to figure out how to count the mount of times an object with a specific key value pair(e.g. "name": "John Amos") exists in a JSON array using PHP and echoing it. Below is my JSON data.
{
"main": {
"request": "40"
},
"data": {
"page": 1,
"posts": [
{
"id": "1",
"name": "John Amos",
"used_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",
"used_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",
"used_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",
"used_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",
"used_id": "A001",
"info": "Sed ut perspiciatis unde omnis iste"
},
{
"id": "6",
"name": "John Amos",
"used_id": "A001",
"info": "Ut enim ad minima veniam"
}
]
}
}
I tried something like this;
$uid_counts = array_count_values($data['data']['posts']);
$username = $uid_counts['John Amos'];
echo $uid_counts;
CodePudding user response:
try this
function countPost(array $arr,$key,$val){
$count=0;
foreach($arr as $ar){
if($ar[$key]==$val){
$count ;
}
}
return $count;
}
$uid_counts = countPost($data['data']['posts'],'name','John Amos');
echo $uid_counts;
i have not tested the code but you got my idea. try it, it should solve your problem