我将提要中的字符串与另一个变量进行比较,并回显相应的字符串。
$xml = @simplexml_load_file($feed);
foreach ($xml->entry as $entry) {
$caller = $entry->caller[0];
$message = $entry->message[0];
}
if (($caller == $id) {
echo '$message';
}
无论($caller==$id)匹配的数量如何,我都希望回显不超过5条消息。
$x=1;
while (($caller == $id) && ($x<=5)) {
echo '$x $message';
$x++;
}
这种普遍做法已经失败。
我想也许我可以把这个条件放在一个函数中,并调用它一定次数,但运气不好。
function myFunction(){
echo '$message';
}
$x=1;
while($x<=5) {
echo '$x';
myFunction();
$x++;
}
例如,您的while循环实际上只输出4个结果,因为您说的是while x小于5,而不是<=5.你可以离开它<5,但是将x改变为等于0而不是1;
第二个问题是,只要$caller不==$id,while循环就会停止。为此,您只需要使用foreach循环,而不需要同时使用foreach来提取数据和使用一段时间来再次循环。
代码的第三个问题是,您在foreach中一遍又一遍地将调用者和消息值写入同一个变量。然后,在while循环中,$caller和$message变量将始终等于$xml->entry数组中的最后一项。
$xml = @simplexml_load_file($feed);
$number_of_results_to_show = 5;
$x = 0; // counter
foreach ($xml->entry as $entry) {
$caller = $entry->caller[0];
$message = $entry->message[0];
if ($caller == $id && $x < $number_of_results_to_show) {
$x++;
echo $message;
}
// also, you can use a break to prevent your loop from continuing
// even though you've already output 5 results
if ($x == $number_of_results_to_show) {
break;
}
}
我假设您有一个数组$xml->entry
,并且您希望打印最多5个数组元素的message[0]
。如果$caller
与$id
匹配,则打印消息。
$xml = @simplexml_load_file($feed);
// Iterate through $xml->entry until the end or until 5 printed messages
for($i = 0, $j = 0; ($i < count($xml->entry)) && ($j < 5); ++$i) {
$caller = $xml->entry[$i]->caller[0];
$message = $xml->entry[$i]->message[0];
if ($caller == $id) {
echo "$message";
++$j;
}
}
如果您想存储$xml->entry
的结果,则:
$xml = @simplexml_load_file($feed);
$storedResults = new array();
foreach($xml->entry as $entry) {
$caller = entry->caller[0];
$message = entry->message[0];
// Store data in array. $storedResults will be an array of arrays
array_push(storedResults, array( 'caller' => $caller, 'message' => $message ));
}
// Print up to 5 messages from the stored results
$i = 0, $j = 0;
while (($i < count($storedResults)) && ($j < 5)) {
if ($storedResults[$i]['caller'] == $id) {
echo $storedResults[$i]['message'];
++$j;
}
++$i;
}