Usman Ahmed
Usman Ahmed

Reputation: 2547

Creating Multi-dimensional array from data in CodeIgniter

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
        )
)

Upvotes: 1

Views: 1145

Answers (3)

Usman Ahmed
Usman Ahmed

Reputation: 2547

I achieve the result with following code. Jeremy Jackson answer gave me idea what should I do to achieve that. But his code didn't work. Thank you Jeremy anyway.

Here is my code:

$cars = array();

$makes = $this->db->select('make')->distinct()->get('vehicles')->result_array();
$makes = array_column($makes, 'make');

foreach($makes as $make) {
    $models = $this->db->where('make', $make)->get('vehicles')->result_array();
    $cars[$make] = array_combine(array_column($models, 'id'), array_column($models, 'name'));
}

print_r($cars);

Upvotes: 1

Hadi
Hadi

Reputation: 2905

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>';

Upvotes: 2

Jeremy Jackson
Jeremy Jackson

Reputation: 2257

Something like this:

$cars = array();

$unique_makes = $this->db->distinct('make')->get('vehicles')->result();

foreach($unique_makes as $make){
    $models = $this->db->where('make', $make)->get('vehicles')->result();
    $cars[$make] = $models;
}

Upvotes: 1

Related Questions