我一直在努力让它发挥作用,虽然我尝试了本网站上其他页面上发布的许多方法,但我都无法让它们发挥作用。
我需要确定最后一个键,这样我的结果最后就不会有了。这听起来很容易,但我似乎无法完成!在这一点上,我猜我只是有一个打字错误或我忽略了什么。如有任何帮助,我们将不胜感激。
这就是我所拥有的:
<?php
$searchString = $_GET["s"];
$prefix = 'http://link_to_my_xml_file.xml?q=';
$suffix = '&resultsPerPage=100';
$file = $prefix . $searchString . $suffix;
if(!$xml = simplexml_load_file($file))
exit('False'.$file);
foreach($xml->results->result as $item) {
echo $item->sku . ",";
}
?>
现在这工作得很好,它只是有一个,在最后:
12345234563456745678,
作为参考,我的xml文件的布局如下:results->result->sku,但其中包含了更多内容。我只是挑出字段。
是否考虑识别第一个?
$first = true;
foreach($xml->results->result as $item) {
if ($first) {
$first = false;
} else {
echo ',';
}
echo $item->sku;
}
使用rtrim()
foreach($xml->results->result as $item) {
$mystr .= $item->sku . ",";
}
echo rtrim($mystr, ",")
应输出:
12345,23456,34567,45678
演示
如果你的键是按数字顺序排列的,比如:0、1、2、3等,这可能是一个解决方案:
foreach($xml->results->result as $key => $item)
{
if( $key > 0 ) echo ", ";
echo $item->sku
}
可能的解决方案#1:
$first = true;
foreach ($xml->results->result as $item) {
if ($first) {
$first = false;
} else {
echo ', ';
}
echo $item->sku;
}
可能的解决方案#2:
$items = array();
foreach ($xml->results->result as $item) {
$items[] = $item->sku;
}
echo join(', ', $items);
您可以将所有内容放在一个字符串中,然后运行:
substr($yourstr, 0, -1);
在你的代码上删除最后一个字符:
http://de1.php.net/manual/en/function.substr.php
或者获取数组中的条目总数,并计算您的位置