从多维数组中选择某个项目

时间:2014-01-25 21:26:38

标签: php

我有一个名为班次的多维数组,其中包含当天(例如星期一)和班次(例如12:00至16:00)

我正在做类似的事情:

$monday = shift from array where day equals Monday

我的阵列目前看起来像是:

Array ( [0] => Array ( [day] => Saturday [shift] => Day Off! ) 
        [1] => Array ( [day] => Sunday [shift] => Day Off! ) 
        [2] => Array ( [day] => Monday [shift] => 11:00-19:00 ) 
        [3] => Array ( [day] => Tuesday [shift] => 08:00-17:00 ) 
        [4] => Array ( [day] => Wednesday [shift] => 08:00-17:00 ) 
        [5] => Array ( [day] => Thursday [shift] => 16:00-01:00 ) 
        [6] => Array ( [day] => Friday [shift] => 16:00-01:00 ) )

使用以下代码构建数组:

$shifts = array();
$sql = mysql_query("SELECT day, shift FROM ps_shifts WHERE user_id = '$user_id' AND week_begin = '$week_1_begin'");
while($row = mysql_fetch_assoc($sql)) {
  $shifts[] = $day;
}

3 个答案:

答案 0 :(得分:0)

您可以将日期用作数组键。

所以:

while($row = mysql_fetch_assoc($sql)) {
  $shifts[$day['day']] = $day;
}

然后你可以通过这样做得到它:

$shift_time = $shifts['Monday']['shift'];

答案 1 :(得分:0)

基于'jd182'anwser解决,但是提供的代码不起作用所以我修改了这个:

$shifts = array();
$sql = mysql_query("SELECT day, shift FROM ps_shifts WHERE user_id = '$user_id' AND week_begin = '$week_1_begin'");

while($row = mysql_fetch_assoc($sql)) {
  $shifts[$row['day']] = $row['shift'];
}

echo $shifts['Monday'];

答案 2 :(得分:0)

/ *要改进上面所说的内容,我们可以采用这样的数据:* /

$data = array(
      array ( 'day' => 'Saturday', 'shift' => 'Day Off!' ),
      array ( 'day' => 'Sunday', 'shift' => 'Day Off!' ),
      array ( 'day' => 'Monday', 'shift' => '11:00-19:00' ),
      /* ... */
      );

/ *我们然后获取该数据并对其进行转换,即将其展平为day => shift。称之为轮班* /

$shifts = array();

$days = array('Saturday','Sunday','Monday','Tuesday','Wednesday','Thursday', 'Friday');

foreach ($data as $i=>$s) {
      $shifts[$days[$i]] = $data[$i]['shift'];

}

/ *这会返回一个数组:

$shifts = array (
'Saturday' => 'Day Off!',
'Sunday' => 'Day Off!',
'Monday' => '11:00-19:00',
    );

* /

/ *然后获得任何一天的转变就像。* /

一样简单
$monday_shift =  $shifts['Monday'];

print "monday shift is:  $monday_shift\n";