简体   繁体   中英

running a foreach loop through a multidimensional array

Hi Im still pretty new to PHP and I want to save three different things in an array that I will be pulling through my database. For now I just need help with setting up the array. For each row of the database theres 3 things I want to sort from, the week of the year(say 43), the hours i worked that week (say 29) , and the year (say 2013). So just to set up the array I put a bunch of fake data like so:

$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)
);

My first question is: Is my array set up properly for what Im trying to describe. My second question: If it is set up correctly, how could I run a foreach loop so I can access all three variables, the week of the year, the hours, and the year?

As I see it, you need it somewhat different way.

There should be some table in a database, with a columns: id , week , hours and year .

So in php equivalent it will be:

$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],
];

Then you can use foreach to find a certain row:

$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;
  }
}

As with your examle you it will break if your arrays by some reason will differ in size.

Additionaly, you can reindex your array by week:

$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;
}

Then a certain week can be easily accessed with $result_indexed[3] for example for week #3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM