我需要一些关于这个数组的帮助我不知道如何根据一些数组值创建一个多维数组。
我有一个普通的数组,让我们说下面的转储输出:
array(
[0] => ("id" => "421", "name" => "element 1", "TYPE" => "1")
[1] => ("id" => "422", "name" => "element 2", "TYPE" => "2")
[2] => ("id" => "423", "name" => "element 3", "TYPE" => "2")
[3] => ("id" => "424", "name" => "element 4","TYPE" => "1")
)
我需要根据" TYPE"创建一个多维数组。键。如果TYPE = 1,则此数组应包含所有具有" TYPE" == 2直到找到下一个数组,TYPE == 1,输出应该是这样的:
array(
[421] => array(
"column" => array("id" => "421", "name" => "element 1", "TYPE" => "1"),
"subcolumns" => array(
[0] => ("id" => "422", "name" => "element 2", "TYPE" => "2"),
[1] => ("id" => "423", "name" => "element 3","TYPE" => "2")
)
)
[424] => array(
"column" => array("id" => "424", "name" => "element 4","TYPE" => "1"),
"subcolumns" => array()
)
)
任何想法,如果我可以用树枝完成这项任务(对我来说会好得多),如果没有,我也可以使用PHP。 我已经尝试构建HTML结构而不更改数组但没有成功。
我需要创建列和" parent"应该是类型为1的项目,所有类型为2的项目都应该是TYPE 1的子项目,以便使用jquery ui对它们进行左右排序。
谢谢!
答案 0 :(得分:2)
一些代码开头:
$new_array = [];
$cur_id = 0;
foreach ($array as $item) {
if ($item['TYPE'] == 1) {
$new_array[$item['id']] = [
'column' => $item,
'subcolumns' => [],
];
$cur_id = $item['id'];
} else {
$new_array[$cur_id]['subcolumns'][] = $item;
}
}