Reputation: 401
I am currently attempting to extract data from a mysql DB and then place it into a multidimensional array, using the device name as a key.
The issue I'm having is that every time I iterate through the results the code im using kills the last item and replaces it.
Here is the code;
##sql connection##
$result = mysql_query(SELECT Device.DeviceID, Device.DeviceName, History.HistoryRec, History.HistoryDetectedDate from Device JOIN History ON Device.DeviceID=History.DeviceID WHERE History.Active_LastRound = 1 AND History.DetectedDate <= $hrs);
if (!$result){
die('invaild query:' . mysql_error());
while($row = mysql_fetch_array($result))
{
$last24hoursarray[$row['DeviceName']] = array($row['HistoryRec']);
}
So the issue i have is that my results set has multiple records with the same device name, and i cant work out how to put them into an array so that they do not overwrite the last item
for example i want
switch1 => issue1
switch1 => issue2
switch1 => issue3
switch2 => issue1
etc
but what i get is;
switch1 => issue3
switch2 => issue1
Thanks in advance. This is the first bit of PHP i have written, so please be gentle :D
Upvotes: 1
Views: 101
Reputation: 21
First of all, arrays only allow a single value for keys. You will not be able to get.
switch1 => issue1
switch1 => issue2
switch1 => issue3
You can get
switch1 => [issue1, issue2, issue3]
I haven't taken the time to test the code, but it would be something like:
while($row = mysql_fetch_array($result)){
if (array_key_exists ( $row['DeviceName'] , $last24hoursarray ){
// append to existing issue.
$last24hoursarray[$row['DeviceName']][] = array($row['HistoryRec']);
} else{
//No device name, create the array with issue.
$last24hoursarray[$row['DeviceName']] = array($row['HistoryRec']);
}
}
Upvotes: 2
Reputation: 3178
It doesn't look like you're using a multi-dimensional array here. A multi-dimensional array is more like this:
switch1 = array(issue1, issue2, issue3);
switch2 = array(issue1);
multi = array(switch1, switch2);
issue = multi[0][1]; // issue2
Upvotes: 0
Reputation: 2164
The reason that this code is not working is that PHP associative arrays only store one value per key of the array. This is so that you can lookup a unique value by key, which is the entire purpose of associative arrays. The code from Merca's example should work great, as it will create an array of values for each key in your associative array.
Upvotes: 0
Reputation: 6159
try creating a new array for each device:
$last24hoursarray[$row['DeviceName']] = new array($row['HistoryRec']);
Upvotes: 0
Reputation: 1960
PHP Array keys are unique, so you would not be able to store multiple values under the same key, try the following:
while($row = mysql_fetch_array($result)) {
$last24hoursarray[$row['DeviceName']][] = $row['HistoryRec'];
}
Upvotes: 5