almost similar like this: PHP/mySQL - how to fetch nested rows into multidimensinal array
SELECT products.NAME, products_prices.PRICE FROM products LEFT JOIN products_prices ON products.ID = products_prices.PROD_ID
this normally would result:
NAME, PRICE
window, 1000
window, 1200
mouse, 1400
because there are two prices for window
and there might be no prices at all. I want it to be resulted in an array:
$arr = array(
array('NAME' => 'window', 'price' => array(
array('PRICE' => 1000),
array('PRICE' => 1200)
),
array('NAME' => 'mouse', 'price' => array(
array('PRICE' => 1400)
)
);
so, the joined record(s) would be sub-arrays. Another problem there can be multiple joins, but only LEFT JOIN-s. How to do this nicely? The linked example put the joined columns to the main part, which I dont want to.
It would look like this:
$dataStore = array();
foreach ($recordSet as $record){
$dataStore[$record['NAME']]['prices'][] = $record['PRICE'];
}
This only works if you know for sure that a single product NAME can have multiple PRICES.
//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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.