问题
I'm trying to get the last item in an array, when being iterated to output something different to a string.
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'];
}
}
However, it keeps adding the AND, meaning that $i == (count($this->condition))
is never true.
How do I resolve this?
回答1:
By far simpler method is to build an array of conditions, then implode
them at the end.
$conditions = array();
foreach($this->condition as $key => $value) {
$conditions[] = $values['columns'] . ' = ' . $value['value'];
}
$query = implode(' and ', $conditions);
回答2:
Arrays in PHP are zero-based. If count()
returns n
, then the last element in your array can be accessed at the n-1
th index.
Hence:
if ($i == (count($this->condition)))
should be
if ($i == (count($this->condition) - 1))
Also, you are incrementing $i
too often. $i++
should be moved outside the foreach
loop. It should be like this:
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++;
}
}
回答3:
The simple way: your if should be
if ($i == count($this->condition)-1) {
as arrays are 0-indexed.
The even simpler way, though - as your code runs out of the while, $i will still be set. Why don't you read it after the while is done, and substract one?
回答4:
I've fixed it.
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'];
}
}
来源:https://stackoverflow.com/questions/13436414/the-last-iteration-in-a-while-loop