phparrayscodeignitermultidimensional-arrayhierarchical

Group rows from a CodeIgniter result set by two columns to create a hierarchical multidimensional array


I have table named 'vehicles' in CodeIgniter project.

+----+---------+--------+
| id | name    | make   |
+----+---------+--------+
|  1 | Corolla | Toyota |
|  2 | Parado  | Toyota |
|  3 | Sunny   | Nissan |
|  4 | Maxima  | Nissan |
|  5 | Premoio | Toyota |
+----+---------+--------+

How can I get multi-dimensional array out of that as shown below:

Array
(
    [Toyota] => Array
        (
            [1] => Corolla
            [2] => Parado
            [5] => Premio
        )

    [Nissan] => Array
        (
            [3] => Sunny
            [4] => Maxima
        )
)

Solution

  • Let's assume that you can get all records from table in a array as in $rows variable.

    $rows = [
        ['id' => 1, 'name' => 'Corolla', 'make' => 'Toyota'],
        ['id' => 2, 'name' => 'Parado', 'make' => 'Toyota'],
        ['id' => 3, 'name' => 'Sunny', 'make' => 'Nissan'],
        ['id' => 4, 'name' => 'Maxima', 'make' => 'Nissan'],
        ['id' => 5, 'name' => 'Premoio', 'make' => 'Toyota']
    ];
    
    $result = [];
    foreach ($rows as $row) {
        $result[$row['make']][$row['id']] = $row['name'];
    }
    

    And just in a single loop you can achieve that. I hope it will help.

    CodeIgniter 3.x

    $query = $this->db->get('vehicles');
    
    $result = [];
    if($this->db->count_all_results() > 0)
    {
        foreach ($query->result_array() as $row)
        {
            $result[$row['make']][$row['id']] = $row['name'];
        }
    }
    
    echo '<pre>';
    print_r($result);
    echo '</pre>';