目前我有这段代码:
<?php
echo '<meta name="robots" content="noindex">';
$arr = json_decode(file_get_contents("http://media1.clubpenguin.com/play/en/web_service/game_configs/ paper_items.json"),true);
foreach($arr as $item) {
$label = $item['label'];
$cost = $item['cost'];
$id = $item['paper_item_id'];
$member = $item['is_member'];
if ($member == "1") {
$member = "Yes";
}else{
$member = "No";
}
echo "$label = $id = $member = $cost";
echo ",<br>";
}
?>
这段代码的作用是它在每一行之后添加一个标签。这是它发生的片段:
echo "$label = $id = $member = $cost";
echo ",<br>";
我想要的是在echo ",<br>";
行的最后一行不要运行。我该怎么做呢?请帮忙!
答案 0 :(得分:9)
试试这个:
$result = array();
foreach($arr as $item) {
...
$result[] = "$label = $id = $member = $cost";
}
echo implode('<br />', $result);
想法是在循环完成工作后将所有行存储在数组中并使用BR标记连接项目。
答案 1 :(得分:1)
试试这个:
<?php
$str = '';
$str .= '<meta name="robots" content="noindex">';
$arr = json_decode(file_get_contents("http://media1.clubpenguin.com/play/en/web_service/game_configs/ paper_items.json"),true);
foreach($arr as $item) {
$label = $item['label'];
$cost = $item['cost'];
$id = $item['paper_item_id'];
$member = $item['is_member'];
if ($member == "1") {
$member = "Yes";
}else{
$member = "No";
}
$str .= "$label = $id = $member = $cost";
$str .= ",<br>";
}
echo substr($str, 0, -5);
?>
答案 2 :(得分:1)
我喜欢ioseb's explode solution,但这里是another easy way:
foreach($arr as $item) {
$first = isset($first) && print ",<br>";
// ...
echo "$label = $id = $member = $cost";
}
这会在第一次迭代之外的所有部分打印换行符 - 但之前文本,只需确保在运行之前未设置$first
。
答案 3 :(得分:0)
我建议您将所有项目存储在字符串中,而不是随时回显。那么你可以删除你想要的任何尾随字符,然后在最后用一个简单的正则表达式回显一次...
echo preg_replace('/\<br\/\>$/','', $myTotalOutputString);
答案 4 :(得分:0)
重写代码:
<?php
echo '<meta name="robots" content="noindex">';
$arr = json_decode(file_get_contents("http://media1.clubpenguin.com/play/en/web_service/game_configs/paper_items.json"), true);
$outArray = array();
foreach($arr as $item) {
$label = $item['label'];
$cost = $item['cost'];
$id = $item['paper_item_id'];
$member = ($item['is_member'] == '1') ? "Yes" : "No";
$outArray[] = "{$label} = {$id} = {$member} = {$cost}";
}
echo implode(',<br>', $outArray);
?>
答案 5 :(得分:-1)
使用rtrim快速单线:
echo rtrim('test <br />', '<br />');
但我投票赞成上面的内容。