0

假设我有这个数组:

$cars = array("Saab","Volvo","BMW","Toyota");

我也有这个 Foreach 循环来“操纵”那个数组:

foreach ($cars as $carsdata) 
    { 
        if (*this is array[0]) {
            do something here
        }else if (*array[1] ... array[x]){
            do another thing here
        }        
    }

知道如何正确编写 Foreach 吗?谢谢。

4

6 回答 6

8

您可以包含一个简单的布尔值,如下所示:

$firstRow=true;
foreach ($cars as $carsdata) 
{ 
    if ($firstRow) 
    {
        $firstRow=false;
        // do something here
    }
    else
    {
        // do another thing here
    }        
}
于 2012-09-26T11:52:45.667 回答
7

在您的情况下,您的数组是数字索引的,所以实际上您可以这样做:

foreach ($cars as $index => $carsdata) 
{ 
    if ($index == 0) { // array[0]
        do something here
    } else { // *array[1] ... array[x]
        do another thing here
    }        
}
于 2012-09-26T11:54:13.087 回答
5

如果您已经像输入的问题那样索引了数组 $cars,那么这将起作用:

foreach ($cars as $i => $carsdata) {
    if (!$i) {
        // do something with first
    } else {
        // do something with second+
    }
}
于 2012-09-26T11:53:21.087 回答
2

这行得通吗?

foreach ($cars as $key => $carsdata) {
     if ($key == 0) {
        //do
    } else {
        //do
    }
}
于 2012-09-26T11:55:42.413 回答
1

另一种可能

$i = 0;
$len = count($carsdata);
foreach ($cars as $carsdata) 
{ 
    if ( $i == 0 ) {
        // first element
        // do something here
    }else if ($i == $len - 1){
        // last element
        // do another thing here
    } else {
        // do the rest here
    } 
    $i++;     
}
于 2012-09-26T11:57:39.123 回答
0
foreach ($cars as $carsdata=>value) 
{ 
    if($value==0){
        // Do the things for the o th index 
    }
    else{


    }
}
于 2012-09-26T12:03:52.287 回答