I grab json filtering with my own json. How to limit foreach for last loop?
JavaScript
x
<?php
$data = '{"page":1,
"results":
[{
"gender": "male",
"language":"English"
},
{
"gender": "male",
"language":"Jerman"
},
{
"gender": "feamle",
"language":"English"
}]}';
$json = json_decode($data, true);
foreach ($json['results'] as $r){
if($r['language'] == "English")
{
echo $r['language']."},{n";
}
}
Output :
JavaScript
English},{
English},{
Expected output :
JavaScript
English},{
English
The point is how to remove / exclude last “},{” in the end of loop?
Advertisement
Answer
Just store the total count of the result, and then if the output line is the last count then do not output the characters },{
So the codes (working) is:
JavaScript
<?php
$data = '{"page":1,
"results":
[{
"gender": "male",
"language":"English"
},
{
"gender": "male",
"language":"Jerman"
},
{
"gender": "feamle",
"language":"English"
}]}';
$json = json_decode($data, true);
$totalcount=0;
foreach ($json['results'] as $r){
if($r['language'] == "English")
{ $totalcount++; }
}
$index=0;
foreach ($json['results'] as $r){
if($r['language'] == "English")
{
$index++;
if ($index!=$totalcount) {
echo $r['language']."},{n"; }
else {
echo $r['language'];}
}
}
?>