I have a database table that contain several projects. I want to show each project in a tab view. so I want to get each project name once and fetch other details under that project name. My table looks like below.
+-------------+----------+--------------+---------+-------------+
| activity_id | activity | project_name | user_id | description |
+-------------+----------+--------------+---------+-------------+
| 1 | A | New Project | 5 | Project |
| 2 | B | New Project | 5 | Project |
| 3 | C | New Project | 5 | Project |
| 4 | D | New Project | 5 | Project |
| 5 | E | New Project | 5 | Project |
| 6 | A | Old Project | 5 | New one |
| 7 | B | Old Project | 5 | New one |
| 8 | C | Old Project | 5 | New one |
| 9 | A | Another One | 5 | Test 01 |
| 10 | B | Another One | 5 | Test 01 |
| 11 | C | Another One | 5 | Test 01 |
| 13 | D | Another One | 5 | Test 01 |
+-------------+----------+--------------+---------+-------------+
Is there a way to get this table like below array?
['New Project'] =>
[0] =>
['activity_Id'] => '1'
['activity'] => 'A'
['user_id'] => '5'
['description'] => 'project'
[1] =>
['activity_Id'] => '2'
['activity'] => 'B'
['user_id'] => '5'
['description'] => 'Project'
and like vice..?
This would do the trick:
$stm = $pdo->query('SELECT * FROM tablename');
while( $row = $stm->fetch(PDO::FETCH_ASSOC) )
{
$info = array(
'activity_id' => $row['activity_id'],
'activity' => $row['activity'],
'user_id' => $row['user_id'],
'description' => $row['description']
);
if( array_key_exists($row['project_name'], $array) && is_array($array[$row['project_name']]) )
{
$array[$row['project_name']][] = $info;
}
else
{
$array[$row['project_name']] = array();
$array[$row['project_name']][] = $info;
}
}
two queries will do it easily, first query to fetch distinct project name and from second query data according to first query project name.
query select distinct project_name from table for loop on this result query select activity_Id, activity, user_id, description from table where project_name = result from first query for loop on this result make array as you wish
No, AFAIK, you can't get this kind of nesting directly with active record -now in CI3 known as Query Builder- (but you probably could achieve it with ORM, frameworks like CakePHP and Laravel have their own implementations).
The only way is to create a new array and iterate over the result array you got from the model in order to build the structure you need.
You can check CI3 docs about Query Builder here: http://www.codeigniter.com/userguide3/database/query_builder.html