I have a table named as demo with fields id
, department
, createddate
and status.
Now i want to fetch all the data from this table to an array with index of array as department and values from each row with same department in that array for example:
Array[department]((Array[0]=>id
createddate
status)
(Array[1]=>id
createddate
status))
Can any one help me please?
You can use the following approach if you can afford to perform a loop on fetched rows and create a new array to meet your required index structure
Once you fetch the db results, perform a loop on the results and push rows into a new array with index as department (I'm assuming its a unique property, and you should even think about renaming it to department_id).
So you easily can do something like this:
<?php
$result = mysql_query('SELECT id, department, createddate, status FROM demo');
$new_array = array();
while($row = mysql_fetch_assoc($result)) {
$department = $row['department'];
// To add enter result row including deparment
$new_array[$department] = $row;
// OR to have only id, createdate, status
$new_array[$department] =
array('id' => $row['id'],
'createdate' => $row['createdate'],
'status' => $row['status']);
}
Note: To have department (department_id) as the index, it must be a unique property.