Php 如何使用深层变量创建多维数组
我有两个单独的数组。数据和深层次Php 如何使用深层变量创建多维数组,php,loops,multidimensional-array,Php,Loops,Multidimensional Array,我有两个单独的数组。数据和深层次 // data array { [0] => "orders", [1] => "order", [2] => "id", [3] => "code", [4] => "products", [5] => "product", [6] => "id", [7] => "title", [8] => "variants", [9] => "variant", [
// data
array {
[0] => "orders",
[1] => "order",
[2] => "id",
[3] => "code",
[4] => "products",
[5] => "product",
[6] => "id",
[7] => "title",
[8] => "variants",
[9] => "variant",
[10] => "id",
[11] => "param",
[12] => "options",
[13] => "option",
[14] => "id",
[15] => "param"
}
及
key($data)==key($deep_级别)
如何像这样从这些数据创建多维数组
array(1) {
["orders"] => array {
["order"] => array {
["id"] => null,
["title"] => null,
["products"] => array {
["product"] => array {
["id"] => null,
["title"] => null,
["variants"] => array {
["variant"] => array {
["id"] => null,
["param"] => null
}
},
["options"] => array {
["option"] => array {
["id"] => null,
["param"] => null
}
}
}
}
}
}
}
深能级不是固定的,它可以更深或更少。我想,这可能是递归
函数()
的事情,但我在这方面是新手。在您的情况下,如果您迭代数组并在数组中存储对以前级别的引用,这可以在没有递归的情况下完成。这样做,整个事情变得非常简单
function buildTree($data, $deep) {
$tree = [];
$levels = [0 => &$tree];
foreach ($data as $i => $item) {
$level = $deep[$i];
$pos = max(0, $level - 1);
$levels[$pos][$item] = [];
$levels[$level] = &$levels[$pos][$item];
$current = $level;
}
return $tree;
}
请注意,此方法没有错误检查,因此您的深层数组应该有效,并以
0
开头,否则输出将是任何内容,但不是您期望的内容。您尝试过任何内容吗?更重要的是,你为什么要把数据存储到两个不同的数组中?你知道怎么做,想得到我的帮助,还是只想告诉我你不喜欢什么。当然,我试过了。否则,我不会在这里寻求帮助。Hi@netoper,询问您的尝试是为了更好地帮助您。如果你展示你所做的尝试和没有达到预期效果的东西,你会更容易发现问题所在。请不要拒绝要求更多细节和背景的评论。对不起,我有点紧张,因为我花了更多的时间在这件事上,但没有成功。你是对的。问题是-如果可能的话,我会解决这两个数组的源代码,因为它容易出错(即,如果第二个数组是[0,1,4]
),而我目前认为在两个数组中存储树结构没有任何好处。谢谢!只是为了澄清。这是整件事()的示例,我正在寻找解决方法。你的代码非常有用。
function buildTree($data, $deep) {
$tree = [];
$levels = [0 => &$tree];
foreach ($data as $i => $item) {
$level = $deep[$i];
$pos = max(0, $level - 1);
$levels[$pos][$item] = [];
$levels[$level] = &$levels[$pos][$item];
$current = $level;
}
return $tree;
}