将mysql数据提取到多维数组的最佳方法是什么?
SQL:
SELECT tariff, monthly_cost, point, phones.name FROM phoneplanpoint
LEFT JOIN phones on phoneplanpoint.phone_id = phones.phone_id
LEFT JOIN price_plans on price_plans.priceplan_id = phoneplanpoint.priceplan_id
输出:
tariff monthly_cost point name
Matrix 15.00 6.0 Blackberry
Matrix 20.00 10.0 Blackberry
Lion 15.00 12.5 Blackberry
Lion 20.00 14.5 Blackberry
Matrix 15.00 6.5 Iphone
Matrix 20.00 7.5 Iphone
我正在尝试将这些数据放入多维数组中,因此很容易为布局视图准备输出数据。
这是测试的一个快速示例,这是正确的方法吗?当然我会用循环。
$Priceplan['Blackberry'] = array();
$Priceplan['Blackberry']['tariff'][] = array("Name" => "Matrix 15.00", "Point" => "6.0");
$Priceplan['Blackberry']['tariff'][] = array("Name" => "Matrix 20.00", "Point" => "10.0");
我希望视图布局数据如下所示:
答案 0 :(得分:1)
假设您的查询返回的数据格式如下:
,以下内容应该可以帮到您$data = array(
array(
'tariff' => 'Matrix',
'monthly_cost' => '15.00',
'point' => '6.0',
'name' => 'Blackberry'
),
array(
'tariff' => 'Matrix',
'monthly_cost' => '20.00',
'point' => '10.0',
'name' => 'Blackberry'
),
array(
'tariff' => 'Lion',
'monthly_cost' => '15.00',
'point' => '12.5',
'name' => 'Blackberry'
),
array(
'tariff' => 'Lion',
'monthly_cost' => '20.00',
'point' => '14.5',
'name' => 'Blackberry'
),
array(
'tariff' => 'Matrix',
'monthly_cost' => '15.00',
'point' => '6.5',
'name' => 'Iphone'
),
array(
'tariff' => 'Matrix',
'monthly_cost' => '20.00',
'point' => '7.5',
'name' => 'Iphone'
)
);
可能有更好的方法可以做到这一点,但它至少是一个开始
foreach ($data as $plan) {
if (!isset($output[$plan['name']])) {
$output[$plan['name']] = array();
}
$options = array(
'name' => $plan['tariff'],
'price' => $plan['monthly_cost'],
'point' => $plan['point']
);
$output[$plan['name']][] = $options;
}
var_dump($output);
将输出您的数据
array(2) {
["Blackberry"] => array(4) {
[0] => array(3) {
["name"] => string(6) "Matrix"
["price"] => string(5) "15.00"
["point"] => string(3) "6.0"
}
[1] => array(3) {
["name"] => string(6) "Matrix"
["price"] => string(5) "20.00"
["point"] => string(4) "10.0"
}
[2] => array(3) {
["name"] => string(4) "Lion"
["price"] => string(5) "15.00"
["point"] => string(4) "12.5"
}
[3] => array(3) {
["name"] => string(4) "Lion"
["price"] => string(5) "20.00"
["point"] => string(4) "14.5"
}
}
["Iphone"] => array(2) {
[0] => array(3) {
["name"] => string(6) "Matrix"
["price"] => string(5) "15.00"
["point"] => string(3) "6.5"
}
[1] => array(3) {
["name"] => string(6) "Matrix"
["price"] => string(5) "20.00"
["point"] => string(3) "7.5"
}
}
}
最后,如果你想确保它运作良好,请务必在查询中添加订单(在电话名称和资费上)。此代码不会处理重复项。如果你想稍微使用这个代码,可以使用array_unique完成,并确保使用SORT_REGULAR optionnal参数。