Hugo Trial Hugo Trial - 2 months ago 10
MySQL Question

Modify an array

I've got an array generated thanks to a MySQL query to my database it's like it :

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
)

)

)


I'd like it to be like this :

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
)

)

)


I just don't understand the logic in those array (I'm pretty sure it's because I'm stressed and really busy though). Can someone help me with that ?

Another solution would be to change the MySql query maybe, I'm obtaining this array thanks to a php Class in which I use two methods :

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);
}


In my controller I get the shown array using that piece of code :

$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>";

Answer

Changing for-loop in controller should do the trick:

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