由于对我的数据库的MySQL查询,我已经生成了一个数组:
Array
(
[0] => Array
(
[0] => Array
(
[id_device] => 1
[device_name] => iPhone 5
[device_brand] => Apple
)
[1] => Array
(
[id_device] => 2
[device_name] => iPhone 4/4S
[device_brand] => Apple
)
)
[1] => Array
(
[0] => Array
(
[id_device] => 3
[device_name] => Galaxy S4
[device_brand] => Samsung
)
[1] => Array
(
[id_device] => 4
[device_name] => Galaxy S3
[device_brand] => Samsung
)
)
)
我希望它是这样的:
Array
(
[Apple] => Array
(
[0] => Array
(
[id_device] => 1
[device_name] => iPhone 5
)
[1] => Array
(
[id_device] => 2
[device_name] => iPhone 4/4S
)
)
[Samsung] => Array
(
[0] => Array
(
[id_device] => 3
[device_name] => Galaxy S4
)
[1] => Array
(
[id_device] => 4
[device_name] => Galaxy S3
)
)
)
我只是不理解那些数组中的逻辑(我很确定这是因为我很紧张而且非常忙)。有人可以帮我吗?
另一种解决方案可能是更改MySql查询,我正在获取此数组,这要归功于我使用两种方法的php类:
public static function getDevicesBrands()
{
$sql = 'SELECT DISTINCT '._DB_PREFIX_.'device.device_brand
FROM '._DB_PREFIX_.'device';
$rq = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($sql);
return ($rq);
}
public static function getDevicesByBrand($brand)
{
$sql = 'SELECT id_device, device_name, device_brand
FROM '._DB_PREFIX_.'device
WHERE '._DB_PREFIX_.'device.device_brand = "'.$brand.'"';
$rq = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($sql);
return ($rq);
}
在我的控制器中,我使用该段代码获取显示的数组:
$device_brand = Device::getDevicesBrands();
$row = count($device_brand);
$devices_by_brand = array();
for ($i = 0; $i <= $row - 1; $i++) {
array_push($devices_by_brand, Device::getDevicesByBrand($device_brand[$i]['device_brand']));
}
echo"<pre>";
print_r($devices_by_brand);
echo"</pre>";
答案 0 :(得分:4)
在控制器中更改for
- 循环应该可以解决问题:
for ($i = 0; $i <= $row - 1; $i++) {
$brand = $device_brand[$i]['device_brand'];
$devices_by_brand[$brand] = Device::getDevicesByBrand($brand);
}