我正在处理一个数据集,该数据集来自一个非常复杂的视图,在一个非常大且复杂的数据库中具有多个子选择和对多个表的连接。
每条记录都有一个这样的结构:
MainValue = XXTS10, qtyPlaceholder1, qtyPlaceholder2, qtyPlaceholder3..., actualQty = 3, qtyPlaceholderKey = 1, color = blue.
MainValue = XXTS10, qtyPlaceholder1, qtyPlaceholder2, qtyPlaceholder3..., actualQty = 10, qtyPlaceholderKey = 3, color = blue.
MainValue = XXTS10, qtyPlaceholder1, qtyPlaceholder2, qtyPlaceholder3..., actualQty = 9, qtyPlaceholderKey = 2, color = blue.
所以对于每个color和MainValue值,有多个记录。我需要根据actualQty设置每个qtyPlaceholder的值,其中qtyPlaceholderKey将告诉我在每个qtyPlaceholder中放入什么值,并从许多记录中只导出一条记录,以便最终的单个记录看起来像这样:
MainValue = XXTS10, qtyPlaceholder1 = 3, qtyPlaceholder2 = 9, qtyPlaceholder3 = 10, color = blue.
我知道多年来我已经这样做了数百次,但我只是有心理障碍创建适当的循环结构和条件,以创建一个记录中的许多值映射到占位符正确。尝试在PHP中完成此操作,但重新检查视图并查看是否可以进行调整可能是一个好主意,但如果我可以帮助它,我真的不想走那条路。
有什么建议吗?
您可以在SQL中使用条件聚合来完成此操作。下面是select
形式的查询:
select MainValue,
max(case when qtyPlaceholderKey = 1 then actualQty end) as qtyPlaceholder1,
max(case when qtyPlaceholderKey = 2 then actualQty end) as qtyPlaceholder2,
max(case when qtyPlaceholderKey = 3 then actualQty end) as qtyPlaceholder3,
color
from complexview v
group by MainValue, color;
遍历数组并创建一个以
为索引的新数组- MainValue 颜色
- qtyPlaceholderKey,值为actualValue
然后通过循环遍历新数组并为MainValue, color和所有qtyPlaceholderKeys及其相应的actualValues分配键值对来'扁平化'新数组。
$dbrows = array(
array(
'MainValue' => 'XXTS10',
'actualQty' => 3,
'qtyPlaceholderKey' => 1,
'color' => 'blue',
),
array(
'MainValue' => 'XXTS10',
'actualQty' => 9,
'qtyPlaceholderKey' => 2,
'color' => 'blue',
),
array(
'MainValue' => 'XXTS10',
'actualQty' => 10,
'qtyPlaceholderKey' => 3,
'color' => 'blue',
),
);
$values = array();
foreach($dbrows as $r) {
$values[$r['MainValue']][$r['color']][$r['qtyPlaceholderKey']] = $r['actualQty'];
}
$result = array();
foreach($values as $mainValue => $colorValues) {
foreach($colorValues as $color => $qtyPlaceholderValues) {
$row = array('MainValue' => $mainValue, 'color' => $color);
foreach($qtyPlaceholderValues as $qtyPlaceholderKey => $actualQty) {
$row["qtyPlaceholderKey$qtyPlaceholderKey"] = $actualQty;
}
$result[] = $row;
}
}
print_r($result);