我有一张名为' vehicle'在CodeIgniter项目中。
+----+---------+--------+
| id | name | make |
+----+---------+--------+
| 1 | Corolla | Toyota |
| 2 | Parado | Toyota |
| 3 | Sunny | Nissan |
| 4 | Maxima | Nissan |
| 5 | Premoio | Toyota |
+----+---------+--------+
如何从中获取多维数组,如下所示:
Array
(
[Toyota] => Array
(
[1] => Corolla
[2] => Parado
[5] => Premio
)
[Nissan] => Array
(
[3] => Sunny
[4] => Maxima
)
)
答案 0 :(得分:2)
假设您可以像$rows
变量一样从数组中的表中获取所有记录。
$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'];
}
只需在一个循环中即可实现。我希望它会有所帮助。
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>';
答案 1 :(得分:1)
这样的事情:
$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;
}
答案 2 :(得分:1)
我使用以下代码实现结果。杰里米杰克逊的回答让我知道我该怎么做才能实现这一目标。但他的代码不起作用。无论如何,谢谢Jeremy。
这是我的代码:
ActiveSheet.ListObjects("CURRENT_ACCOUNT_QUERY_0001").ShowHeaders = False