修改数组


Modify an array

由于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>";

改变控制器中的for循环应该可以做到这一点:

for ($i = 0; $i <= $row - 1; $i++) {
    $brand = $device_brand[$i]['device_brand'];
    $devices_by_brand[$brand] = Device::getDevicesByBrand($brand);
}