-1

由于对我的数据库的 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>";
4

1 回答 1

4

在控制器中更改for-loop 应该可以解决问题:

for ($i = 0; $i <= $row - 1; $i++) {
    $brand = $device_brand[$i]['device_brand'];
    $devices_by_brand[$brand] = Device::getDevicesByBrand($brand);
}
于 2013-08-26T17:20:53.803 回答