0

几乎类似这样:PHP/mySQL - 如何将嵌套行提取到多维数组中

SELECT products.NAME, products_prices.PRICE FROM products LEFT JOIN products_prices ON products.ID = products_prices.PROD_ID

这通常会导致:

NAME,   PRICE
window, 1000
window, 1200
mouse,  1400

因为有两个价格,window可能根本没有价格。我希望它产生一个数组:

$arr = array(
             array('NAME' => 'window', 'price' => array(
                                                        array('PRICE' => 1000),
                                                        array('PRICE' => 1200)
                                                       ),
             array('NAME' => 'mouse', 'price' => array(
                                                       array('PRICE' => 1400)
                                                      )
            );

因此,连接的记录将是子数组。另一个问题可以有多个连接,但只有 LEFT JOIN-s。如何很好地做到这一点?链接的示例将连接的列放在主要部分,我不想这样做。

4

2 回答 2

2

它看起来像这样:

 $dataStore = array();
 foreach ($recordSet as $record){
     $dataStore[$record['NAME']]['prices'][] = $record['PRICE'];
 }

仅当您确定单个产品名称可以有多个价格时,这才有效。

于 2012-05-03T13:49:20.470 回答
2
//array you get from mysql:
$arrMysql = array(
             array('NAME' => 'window', 'PRICE' => 1000),
             array('NAME' => 'window', 'PRICE' => 1200),
             array('NAME' => 'mouse', 'PRICE' => 1400)
            );

$arr = array();
foreach ($arrMysql as $row) {
    if (isset($arr[$row['NAME']])) {
        if (isset($arr[$row['NAME']]['price'])) {
            $arr[$row['NAME']]['price'].push(array('PRICE' => $row['PRICE']));
        } else {
            $arr[$row['NAME']]['price'] = array(array('PRICE' => $arr[$row['NAME']]['PRICE']), array('PRICE' => $row['PRICE']));
            unset($arr[$row['NAME']]['PRICE']);
        }
    }
    else {
        $arr[$row['NAME']] = $row;
    }
}

//you get:

$arr = array(
             'window' => array('NAME' => 'window', 'price' => array(
                                                        array('PRICE' => 1000),
                                                        array('PRICE' => 1200)
                                                       ),
             'mouse' => array('NAME' => 'mouse', 'price' => array(
                                                       array('PRICE' => 1400)
                                                      )
            );

// and if you want your array:
$arr = array_values($arr);
于 2012-05-03T13:58:54.037 回答