如何在PHP中创建此数组?

时间:2014-02-22 02:25:31

标签: php sql arrays while-loop array-push

属性DB:

   cod_atr=1 value=Color 
   cod_atr=2 value=Size

每个属性DB的值:

   cod_atr_val=1, cod_atr=1, value='Blue'
   cod_atr_val=2, cod_atr=1, value='Green'
   cod_atr_val=3, cod_atr=2, value='S'
   cod_atr_val=4, cod_atr=2, value='M'
   cod_atr_val=5, cod_atr=2, value='L'

数组结果我正在寻找

$attr[0] = array('attr' => 'Color', 'values' => array('Blue', 'Green') ) ;
$attr[1] = array('attr' => 'Size', 'values' => array('S','M','L') ) ;

我试过以下但是我没有把它弄得很正确

$rs_attr = $DB->Execute(SQL);
while ($arrayattr = $rs_attr->FetchRow()){

   $rs_attr_values = $DB->Execute(SQL);
   while ($arrayattr_values = $rs_attr_values->FetchRow()) {

   }

}

有什么想法吗? 感谢

1 个答案:

答案 0 :(得分:0)

使用SQL:

SELECT a.value AS attr, GROUP_CONCAT(v.value) AS `values`
FROM Attributes a
JOIN Values_of_Attributes v ON a.cod_atr = v.cod_atr
GROUP BY attr

然后你的循环将是:

$attr = array();
while ($row = $rs_attr->FetchRow()) {
    $row['values'] = explode(',', $row['values']);
    $attr[] = $row;
}