2013-08-26 100 views
-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>"; 
+0

我想你已经解决了,那么问题是什么? –

回答

4

改变在控制器for -loop应该做的伎俩:

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

非常感谢...你太棒了,它非常简单,我只需要用数组进行训练。 一旦有可能,我会接受你的回答(你在7分钟内回复xD)。 –