while循环中的最后一次迭代

时间:2012-11-18 00:52:07

标签: php while-loop

我正在尝试获取数组中的最后一项,当迭代输出不同于字符串的内容时。

if (count($this->condition) > 1) {
        $i=0;
        while ($i < count($this->condition)){
            if ($i == (count($this->condition) -1)) {

                foreach ($this->condition as $key => $value){

                    $query .= $value['columns']." = ".$value['value'];
                }
            } else {
                foreach ($this->condition as $key => $value){

                    $query .= $value['columns']." = ".$value['value']." AND ";
                    $i++;

                }
            }
        }
    } else {
        foreach ($this->condition as $key => $value){
            $query .= $value['columns']." = ".$value['value'];

        }
    }

但是,它会不断添加AND,这意味着$i == (count($this->condition))永远不会成真。

如何解决此问题?

4 个答案:

答案 0 :(得分:3)

到目前为止,更简单的方法是建立一个条件数组,然后在最后implode

$conditions = array();
foreach($this->condition as $key => $value) {
   $conditions[] = $values['columns'] . ' = ' . $value['value'];
}
$query = implode(' and ', $conditions);

答案 1 :(得分:1)

PHP中的数组是从零开始的。如果count()返回n,则可以在n-1索引处访问数组中的最后一个元素。

因此:

if ($i == (count($this->condition)))

应该是

if ($i == (count($this->condition) - 1))

此外,您经常递增$i$i++应该移到foreach循环之外。它应该是这样的:

while ($i < count($this->condition)) {
    if ($i == (count($this->condition) -1)) {
        foreach ($this->condition as $key => $value){
            $query .= $value['columns']." = ".$value['value'];
        }
    } else {
        foreach ($this->condition as $key => $value){
            $query .= $value['columns']." = ".$value['value']." AND ";
        }

        $i++;
    }
}

答案 2 :(得分:0)

简单的方法:你的if应该是

 if ($i == count($this->condition)-1) {

因为数组是0索引的。

虽然更简单的方法 - 因为你的代码耗尽了一段时间,$ i仍然会被设置。你为什么不在完成这段时间之后阅读它,并减去一个?

答案 3 :(得分:0)

我已经修好了。

 if (count($this->condition) > 1) {
            $i=0;
            foreach ($this->condition as $key => $value){

                if ($i == ($conditionCount -1)) {
                    $query .= $value['columns']." = ".$value['value'];
                } else {
                    $query .= $value['columns']." = ".$value['value']." AND ";
                }
            $i++;
            }
    } else {
        foreach ($this->condition as $key => $value){
            $query .= $value['columns']." = ".$value['value'];

        }
    }