我有以下数组。请忽略语法,因为我将其复制为源代码。
<?php
$rowData = Array
(
[1] = Array
(
[0] = Buffalo
[1] = Tampa Bay
[2] = -7
[3] = favorite
[4] = 0
[5] = 46
)
[2] = Array
(
[0] = Minnesota
[1] = Tennessee
[2] = 3
[3] = favorite
[4] = 1
[5] = 33
)
[3] = Array
(
[0] = Green Bay
[1] = Cincinnati
[2] = 3
[3] = favorite
[4] = 1
[5] = 33
)
[4] = Array
(
[0] = Jacksonville
[1] = Buffalo
[2] = 4
[3] = underdog
[4] = 1
[5] = 54
)
);
?>
我想要做的是遍历每个数组,如果[4]条目= 1,则对该数组执行一个函数,如果[4]条目= 0,则执行不同的函数。我不知道如何在循环中识别每一个..
foreach ($rowData as $row => $tr)
{
//if [4] is equal to 1
if()
{
}
//if [4] is equal to 0
elseif()
{
}
}
答案 0 :(得分:0)
如果要在$rowData
的子数组上执行某些功能,以便在循环完成后获得更新版本,则需要执行以下操作:
echo '<pre>',print_r($rowData),'</pre>';
foreach ($rowData as &$tr) // the & sign will pass the sub array $tr as a reference
{
//if [4] is equal to 1
if($tr[4] == 0)
{
execute_function1($tr);
}
//if [4] is equal to 0
elseif($tr[4] == 0)
{
execute_function2($tr);
}
}
// again you need to pass the sub array as a reference in order to make sure that the functionality you are going to apply to the $tr in the following functions will be also applied to the respective $tr of the $rowData array
execute_function1(&$tr){ .. };
execute_function2(&$tr){ .. };
echo '<pre>',print_r($rowData),'</pre>';
我曾经使用echo
语句(一个在循环之前,一个在之后),因此您可以看到$rowData
数组的变化情况。
答案 1 :(得分:0)
试试这个:
foreach($rowData as $array)
{
if($array[4] == 1)
//some action
else
//another ction
}
答案 2 :(得分:0)
你可以这样做,但不要忘记测试$ tr [4]是否存在:
foreach ($rowData as $row => $tr)
{
//Test if the key 4 exists
if(isset($tr[4])) {
//Switch value
switch($tr[4]) {
case 1:
//Do action...
break;
case 0:
//Do action...
break;
default:
//Do nothing...
break;
}
}
}