Skip to content
Advertisement

How to remove last loop from foreach?

I grab json filtering with my own json. How to limit foreach for last loop?

    <?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 :

English},{

English},{

Expected output :

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:

 <?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'];}
     }
}
?>
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement