2013-08-26 137 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)。 –