从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
)
)
我在CodeIgniter项目中有一个名为'vehicles'的表。 p>
+ ---- + --------- + -------- + \ N | id | 名字| make |
+ ---- + --------- + -------- +
| 1 | 卡罗拉| 丰田|
| 2 | Parado | 丰田|
| 3 | Sunny | 日产|
| 4 | 千里马| 日产|
| 5 | Premoio | 丰田|
+ ---- + --------- + -------- +
code> pre>
我怎样才能获得多元化 - 如下所示的三维数组: p>
数组
(
[丰田] =>数组
(
[1] =>卡罗拉\ n [2] => Parado
[5] => Premio
)
[Nissan] =>数组
(
[3] => Sunny
[4] => ; Maxima
)
)
code> pre>
div>
答
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>';
答
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;
}
答
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);