结束php if语句

时间:2013-11-23 02:57:12

标签: php if-statement

我将Feed中的字符串与另一个变量进行比较并回显相应的字符串。

$xml = @simplexml_load_file($feed);

foreach ($xml->entry as $entry) {      
    $caller = $entry->caller[0];
    $message = $entry->message[0];
} 


if (($caller == $id) {
  echo '$message';
}

我想回复不超过5条消息,无论($ caller == $ id)匹配的数量。

 $x=1; 

 while (($caller == $id) && ($x<=5)) {
         echo '$x $message';
         $x++;
 }

这种一般方法失败了。

我想也许我可以把这个条件放在一个函数中并调用它一定次数但没有运气。

function myFunction(){
    echo '$message';
}

$x=1; 

while($x<=5) {
    echo '$x';
    myFunction();
    $x++;   
} 

2 个答案:

答案 0 :(得分:2)

我假设您有一个数组$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;
}

答案 1 :(得分:2)

首先,您的 while循环实际上只会输出4个结果,因为您说的是x小于5而不是&lt; = 5.您可以保留&lt; = 5。 5,但将x改为等于0而不是1;

第二个问题是,只要$来电者没有== $ id,您的 while循环就会停止。你应该只需要使用 foreach循环,而不是提取数据的foreach和再次循环它的一段时间。

您的代码的第三个问题是您在foreach中反复将调用者和消息值写入同一个变量。然后,在while循环中,$ caller和$ message变量将始终等于$ xml-&gt;条目数组中的最后一项。

$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;
    }
}
相关问题