1

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

3 Answers 3

2

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>';
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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

2 Comments

You are doing more than one mysql query in your code where you can do it with a single query. Isn't that? Did you saw my answer?
@HADI sorry I couldn't understand your code first. Now I see this. You showed me the right way.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.