通过多维数组运行foreach循环

时间:2014-01-18 19:58:00

标签: php arrays multidimensional-array foreach

嗨我仍然是PHP的新手,我想在一个数组中保存三个不同的东西,我将通过我的数据库。现在我只需要设置阵列的帮助。对于数据库的每一行,我要排序的是3件事情,一年中的一周(比如43),我工作的那一周(比如29)和年份(比如说2013年)。所以只是为了设置数组我就像这样放了一堆假数据:

$hours = array(
    "week" => array(1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39,41,43,45,47,49,51), 
    "hours" => array(65,56,34,76,87,43,23,43,53,23,65,34,23,54,65,75,34,23,34,54,34,54,65,34,23,76),
     "year" => array(2013,2013,2013,2013,2013,2013,2013,2013,2013,2013,2013,2013,2013,2013,2013,2013,2013,2013, 2014,2014,2014,2014,2014)
);

我的第一个问题是:我的阵列是否正确设置为我试图描述的内容。 我的第二个问题:如果设置正确,我怎么能运行一个foreach循环,这样我就可以访问所有三个变量,一年中的一周,一小时和一年?

1 个答案:

答案 0 :(得分:1)

在我看来,你需要的方式有所不同。

数据库中应该有一些表格,其中有一列:idweekhoursyear

所以在php等价物中它将是:

$result = [
  ['id' => 1, 'week' => 1,  'hours' => 40, 'year' => 2014],
  ['id' => 2, 'week' => 3,  'hours' => 53, 'year' => 2014],
  ['id' => 3, 'week' => 14, 'hours' => 32, 'year' => 2014],
];

然后你可以使用foreach来找到某一行:

$target = 3; # assume target week we trying to search is 3

$row_found = null;   

foreach($result as $row) {
  if($row['week'] == $target) {
    $row_found = $row;

    break;
  }
}

与您的考试一样,如果您的阵列由于某种原因在大小上不同,它将会中断。

另外,您可以按周重新索引数组:

$result = [ # that's result from mysql
  ['id' => 1, 'week' => 1,  'hours' => 40, 'year' => 2014],
  ['id' => 2, 'week' => 3,  'hours' => 53, 'year' => 2014],
  ['id' => 3, 'week' => 14, 'hours' => 32, 'year' => 2014],
];

$result_indexed = [];

foreach($result as $row) {
  $result_indexed[$row['week']] = $row;
}

然后可以使用$result_indexed[3]轻松访问某个星期,例如第3周