循环遍历多维数组php



我有以下数组。请忽略语法,因为它是从源代码复制过来的。

<?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()
  {
  }
}

如果你想在$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数组是如何变化的。

试试这个:

foreach($rowData as $array)
{
    if($array[4] == 1)
       //some action
    else
       //another ction
}

你可以这样做,但不要忘记测试$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;
           }
        }
    }

您可以使用递归算法遍历所有JSON数组,如果遇到键值为4的元素,则根据值为0或1调用不同的函数。

recursiveArray($rowData);
# A recursive function to traverse the $rowData array
function recursiveArray(array $rowData)
{
    foreach ($rowData as $key => $hitElement) {
        # If there is a element left
        if (is_array($hitElement)) {
            # call recursive structure to parse the $rowData
            recursiveArray($hitElement);
        } else {
            if ($key == 4) {
                switch($hitElement) {
                    case 1: 
                        echo 'Calling fn();' . PHP_EOL;
                        break;
                    case 0:
                        echo 'Calling differentfn();' . PHP_EOL;
                        break;
                }
            }
        }
    }
}

Live code ->https://wtools.io/php-sandbox/bFEO

相关内容

  • 没有找到相关文章

最新更新