我有一个在PHP中运行的查询,该查询获取一些MySQL数据并将其作为对象返回。我将数据分组,但是它在对象中返回结果,每个组都是对象属性。我希望结果以数组形式返回
我希望将$ data变量作为由service_type分组的数组返回,但它是一个对象。
从mysql采样数据
id, service_name, service_type
1, 'oil change', 'fluids'
2, 'tire rotation', 'tires';
3, 'power steeling fluid', 'fluids'
public function fetchAllServices() {
$q = $this->db->query("SELECT id, service_name, service_type FROM services ORDER BY service_type, id");
if ($this->db->affected_rows() > 0) {
foreach ($q->result() as $a) {
$data[] = $a;
}
} else {
error_log('No Services Found.)');
return false;
}
foreach( $data as $key => $service ){
$categories[$service->service_type][] = $service;
$service->service_name = str_replace('-', ' ', $service->service_name );
}
$data = $categories ? $categories : $data;
return $data;
}
前端javascript上的预期结果
$data: [
0: {
category: 'fluids'
results: [
{id: 1, service_name: 'oil change', service_type: 'fluids'}
{id: 3, service_name: 'power steering fluid', service_type: 'fluids'}
]
}
1: {
category: 'tires'
results: [
{id: 2, service_name: 'tire rotation', service_type: 'tires'}
]
}
];
当前结果:
$data: {
'fluids': [
{id: 1, service_name: 'oil change', service_type: 'fluids'}
{id: 3, service_name: 'power steering fluid', service_type: 'fluids'}
]
'tires': [
{id: 2, service_name: 'tire rotation', service_type: 'tires'}
]
};