简体   繁体   中英

removing a “,” from the last element in a foreach loop?

i am trying (like hell..) to remove ',' from the last element in a foreach loop. tried several counter methods, but not really successfully.

[<?php

function fetchData($url){
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_TIMEOUT, 20);
  $result = curl_exec($ch);
  curl_close($ch); 
  return $result;
  }

  $result = fetchData("https://api.instagram.com/v1/users/XXXXXXX/media/recent/?access_token=XXXXXXX&count=10");

  $result = json_decode($result);
  foreach ($result->data as $post) {
     echo '{"name":"Hello","imgpath":"  ';echo $post->images->low_resolution->url;echo '"},';

  }

?>]

Use json_encode()

<?php 
...

$json = array();
foreach ($result->data as $post){
    $json[]=array(
        'name'=>'Hello',
        'imgpath'=>$post->images->low_resolution->url,
    );
}

header('Content-Type: application/json');
exit(json_encode($json));
?>

Store the whole thing in a string instead of echoing it, then you can cut the last character using $string=substr($string,0,-1);

[<?php

function fetchData($url){
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_TIMEOUT, 20);
  $result = curl_exec($ch);
  curl_close($ch); 
  return $result;
}

$result = fetchData("https://api.instagram.com/v1/users/XXXXXXX/media/recent/?access_token=XXXXXXX&count=10");

$string="";

$result = json_decode($result);
foreach ($result->data as $post) {
     $string.='{"name":"Hello","imgpath":"' . $post->images->low_resolution->url . '"},';

}

echo substr($string,0,-1);

?>]

Maybe something like:

// quick and dirty solution
foreach ($result->data as $index => $post) {
    $comma = ',';
    if ((int) $index === count($result->data) -1) {
        $comma = '';
    }
    $string.='{"name":"Hello","imgpath":"  ';echo $post->images->low_resolution->url;echo '"}'.$comma;
}

I would use implode, quite cleaner:

$result = json_decode($result);

$string = '{"name":"Hello","imgpath":"';
$string .= implode( '}, {"name":"Hello","imgpath":"', $result->data );
$string .= '}';

echo $string;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM