我有一个MySQL查询,返回数据转储喜欢这样(重复预期的和所需要的被排除此问题的其他列):
SessionID DayofWeek SessionDetails Description
1 Sunday 1:00 PM Foo
1 Sunday 1:00 PM Foo
1 Sunday 1:00 PM Foo
1 Sunday 1:00 PM Foo
2 Monday 10:00 AM Foo
2 Monday 10:00 AM Foo
2 Monday 10:00 AM Foo
2 Monday 10:00 AM Foo
3 Monday 7:00 PM Barr
3 Monday 7:00 PM Barr
3 Monday 7:00 PM Barr
3 Monday 7:00 PM Barr
我试图为每天创建一个数组,并且只在其中存储一次不同的会话/时间,例如
Sunday => Array (
[SessionID] => 1
[SessionDetails] => 1:00 PM
[Description] => Foo
)
Monday=> Array (
[SessionID] => 2
[SessionDetails] => 10:00 AM
[Description] => Foo
[SessionID] => 3
[SessionDetails] => 7:00 PM
[Description] => Bar
)
我在foreach ($sqlresults as $row)
循环之前的每一天都设置一个空白数组,例如$sunday=array(); $monday=array();
等。
然后在循环中执行以下操作:
if (!in_array($row['SessionID'],$sunday)){
$sunday[]=array($row['SessionID'],$row['Description'], $row['SessionDetails']);
}
它可以正常工作,但不会检查if(!in_array)部分是否正确,而是将每个(重复的)SessionID添加为新数组,例如,
print_r($sunday)
Array
(
[0] => Array
(
[0] => 1
[1] => Foo
[2] => 1 PM
)
[1] => Array
(
[0] => 1
[1] => Foo
[2] => 1 PM
)
[2] => Array
(
[0] => 1
[1] => Foo
[2] => 1 PM
)
[3] => Array
(
[0] => 1
[1] => Barr
[2] => 1 PM
)
[4] => Array
(
[0] => 2
[1] => Barr
[2] => 10 AM
)
等...
我尝试在添加到数组之前检查数组中的sessionID:
if (!in_array($row['SessionID'][],$sunday)){
但是“致命错误:无法使用[]进行阅读”
所以我尝试了:
if (!in_array($sunday[$row['SessionID']],$sunday)){
但是“注意:未定义的偏移量:1”
我尝试将其设置为关联值:
if (!in_array($row['SessionID'],$sunday)){
$sunday[]=array("SessionID"=>($row['SessionID']),"Description"=>($row['Description']), "Time"=>($row['SessionDetails']));
}
相同的问题,除了数组更易于阅读:
[0] => Array
(
[SessionID] => 1
[Description] => Foo
[Time] => 1 PM
)
[1] => Array
(
[SessionID] => 1
[Description] => Foo
[Time] => 1 PM
)
TLDR:在尝试添加到日期数组之前,如何获取它来检查索引[SessionID]?