假设我有一些看起来像这样的数据库行:
group version tool info
group_a m screwdriver for screwing things
group_a m hammer for hitting things
group_a l screwdriver for screwing things
group_a xl screwdriver for screwing things
group_b m screwdriver for screwing things
group_b m hammer for hitting things
group_b m wrench for wrenching things
group_b l screwdriver for screwing things
group_b xl wrench for wrenching things
从那里我想创建和看起来像这样的数组:
array(
array( 'id' => 'group_a',
array( 'id' => 'm',
array( 'id' => 'screwdriver',
'info' => 'for screwing things'
),
array( 'id' => 'hammer',
'info' => 'for hitting things'
),
),
array( 'id' => 'l',
array( 'id' => 'screwdriver',
'info' => 'for screwing things'
),
),
array( 'id' => 'xl',
array( 'id' => 'screwdriver',
'info' => 'for screwing things'
),
)
array( 'id' => 'group_b',
array()
)
~~~~~~~ etc ~~~~~~~
);
对于一些上下文我将它作为JSON从Zend传递给BackboneJS,然后将这些数组用于Group Collection,其中包含n个版本集合,其中包含n个工具模型。
任何帮助都很受欢迎,很高兴澄清任何要点。
干杯。
答案 0 :(得分:0)
我真的不喜欢这样,因为它会像疯了一样发出通知。但最终结果将是这样的:
$array = array();
while($row = fetch($query) {
$array['id'][$row['group']]['id'][$row['version']]['id'] = $row['tool'];
$array['id'][$row['group']]['id'][$row['version']]['info'] = $row['info'];
}
我会使用issets使其更优雅,并检查以防止被覆盖并附加到。
我可能会使用实际ID作为键而不是单词来帮助实现唯一性。
无论如何,这应该有助于你思考正确的方向。
答案 1 :(得分:0)
将您的数据转换为三维临时数组。
$temparray=array();
foreach ($rows as $row) {
$temparray[$row['group']][$row['version']][$row['tool']]=$row['info'];
}
这个临时数组看起来与你想要实现的类似,但不完全相同:
Array
(
[group_a] => Array(
[m] => Array(
[screwdriver] => for screwing things
[hammer] => for hitting things
)
[l] => Array(
[screwdriver] => for screwing things
)
[xl] => Array(
[screwdriver] => for screwing things
)
)
[group_b] => Array(
[m] => Array(
[screwdriver] => for screwing things
[hammer] => for hitting things
[wrench] => for wrenching things
)
[l] => Array(
[screwdriver] => for screwing things
)
[xl] => Array(
[wrench] => for wrenching things
)
)
)
现在要么足以满足您的需求,要么必须重现您所显示的确切结构。在后一种情况下,只需循环遍历该临时数组即可实现目标:
foreach ($temparray as $groupid=>$groupdata) {
$grouparray=array('id'=>$groupid);
foreach ($groupdata as $versionid=>$versiondata) {
$versionarray=array('id'=>$versionid);
foreach ($versiondata as $toolid=>$tooldata) {
$toolarray=array('id'=>$infoid,'info'=>$tooldata);
$versionarray[]=$toolarray;
}
$grouparray[]=$versionarray;
}
$targetarray[]=$grouparray;
}
你已经完成了:)
BTW,具有'id',0,1,2,...作为索引的数组有点尴尬。我不知道BackboneJS,但任何使用这种格式的脚本(而不是temptable的样子)对我来说都很可疑。