假设我有这个数组:
$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?感谢。
答案 0 :(得分:8)
你可以包含一个像这样的简单布尔值:
$firstRow=true;
foreach ($cars as $carsdata)
{
if ($firstRow)
{
$firstRow=false;
// do something here
}
else
{
// do another thing here
}
}
答案 1 :(得分:7)
在您的情况下,您的数组是编号索引的,所以实际上您可以这样做:
foreach ($cars as $index => $carsdata)
{
if ($index == 0) { // array[0]
do something here
} else { // *array[1] ... array[x]
do another thing here
}
}
答案 2 :(得分:5)
如果你已经为你输入的数组$ car建立索引,那么这将有效:
foreach ($cars as $i => $carsdata) {
if (!$i) {
// do something with first
} else {
// do something with second+
}
}
答案 3 :(得分:2)
这会有用吗?
foreach ($cars as $key => $carsdata) {
if ($key == 0) {
//do
} else {
//do
}
}
答案 4 :(得分: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++;
}
答案 5 :(得分:0)
foreach ($cars as $carsdata=>value)
{
if($value==0){
// Do the things for the o th index
}
else{
}
}