Reputation: 305
I have a MySQL query that returns a dump of data like so (duplicates expected and needed for other columns that are excluded for this question):
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
I am trying to create an array for each day and only store the different session/times once in it, e.g.,
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
)
I am setting a blank array for each day before my foreach ($sqlresults as $row)
loop, like $sunday=array(); $monday=array();
etc.
Then inside the loop I am doing:
if (!in_array($row['SessionID'],$sunday)){
$sunday[]=array($row['SessionID'],$row['Description'], $row['SessionDetails']);
}
It sort-of-works but it's not checking the if (!in_array) part right and it's adding every single (duplicate) SessionID as a new array e.g.,
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
)
etc...
I tried to check the sessionID inside the array before adding to it:
if (!in_array($row['SessionID'][],$sunday)){
But "Fatal error: Cannot use [] for reading"
So I tried:
if (!in_array($sunday[$row['SessionID']],$sunday)){
But "Notice: Undefined offset: 1"
I tried setting it to associative values:
if (!in_array($row['SessionID'],$sunday)){
$sunday[]=array("SessionID"=>($row['SessionID']),"Description"=>($row['Description']), "Time"=>($row['SessionDetails']));
}
Same problem, except the array is easier to read:
[0] => Array
(
[SessionID] => 1
[Description] => Foo
[Time] => 1 PM
)
[1] => Array
(
[SessionID] => 1
[Description] => Foo
[Time] => 1 PM
)
TLDR: How can I get it to check the index [SessionID] before trying to add to the day array?
Upvotes: 0
Views: 46
Reputation: 403
Here's a simple way to do it using array_unique
.
$result = [];
foreach (array_unique($rows, SORT_REGULAR) as $row) {
$result[$row['DayofWeek']][] = $row;
}
You can run the code here.
Upvotes: 1