在我的PHP应用程序中,从DB获取结果。处理完结果后,我需要使用foreach
转换结果如下Array
(
[1] => Array -----> This is intent 1, this key indicates all intent values which is equal to 1, should belongs to here.
(
[0] => Array
(
[name] => A
[indent] => 1
)
[1] => Array
(
[name] => B
[indent] => 1
)
)
[2] => Array
(
[0] => Array
(
[name] => B
[indent] => 2
)
[1] => Array
(
[name] => A
[indent] => 2
)
)
[3] => Array
(
[0] => Array
(
[name] => A
[indent] => 3
)
)
)
我有一些常见的意图值,常见的意图值存储在数组中,如数组('1'=&gt;数组(数组[0],数组[1])); 。< / p>
我尝试的是
foreach($results as $data){
$root_array[$data['intent']] = array($data);
}
这将替换旧数组并插入常用的最后一个意图值。
我得到如下结果,意图1和意图2被最后数据替换
Array
(
[1] => Array
(
[0] => Array
(
[name] => B
[indent] => 1
)
)
[2] => Array
(
[0] => Array
(
[name] => A
[indent] => 2
)
)
[3] => Array
(
[0] => Array
(
[name] => A
[indent] => 3
)
)
)
答案 0 :(得分:2)
在循环中,您必须检查当前缩进是否已初始化。如果没有,则创建它,否则只需将新数据附加到它。
foreach($results as $data) {
if (!isset($root_array[$data['indent']])) {
$root_array[$data['indent']] = array($data);
} else {
$root_array[$data['indent']][] = $data;
}
}