从foreach循环中的最后一个元素中删除“,”?

时间:2014-04-24 12:14:38

标签: php

我正在尝试(像地狱......)删除','来自foreach循环中的最后一个元素。 尝试了几种计数器方法,但并没有真正成功。

[<?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 '"},';

  }

?>]

4 个答案:

答案 0 :(得分:4)

使用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));
?>

答案 1 :(得分:1)

将整个事物存储在字符串中而不是回显它,然后您可以使用$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);

?>]

答案 2 :(得分:0)

可能是这样的:

// 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;
}

答案 3 :(得分:-1)

我会使用implode,相当清洁:

$result = json_decode($result);

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

echo $string;