我有一个这样的输入数组
$input = [
["relation" => "OR"],
["color" => 'green'],
["color" => 'yellow'],
["relation" => "AND"],
["color" => 'black'],
["color" => 'orange'],
["relation" => "OR"],
["color" => 'blue'],
["color" => 'violet'],
];
期望的结果:
$output = array(
'relation' => 'OR',
array(
"color" => 'green'
),
array(
"color" => 'yellow'
),
array(
"relation" => "AND",
array(
"color" => "black"
),
array(
"color" => "orange"
),
array(
"relation" => "OR",
array(
"color" => "blue"
),
array(
"color" => "violet"
),
)
)
);
我相信我需要做递归函数来处理这个。
我有这个,但只适用于一个级别
function generate_nested_array($array, $nested_tax_query = array(), $target_index = 0)
{
//the first element is always the relation
$nested_tax_query['relation'] = $array[0]['relation'];
// unset the first element as it is not needed anymore
unset($array[0]);
$len = count($array);
// reindex the array
$array = array_values($array);
foreach ($array as $element_key => $element) {
if (isset($element['relation'])) {
$target_index = $element_key;
break;
}
}
// put everything below the target index into the target index and leave the rest as it is
for ($i = 0; $i < $len - 1; $i++) {
if ($i < $target_index) {
$nested_tax_query[] = $array[$i];
} else {
$nested_tax_query[$target_index][] = $array[$i];
}
}
// last item in the nested array
$len_nested = count($nested_tax_query);
// last item in the in the nested array
$last_item_in_nested_array = $nested_tax_query[$len_nested - 2];
return $nested_tax_query;
}
我的做法对吗?
我没有看到使用递归的意义。我发现引用变量是一种更直观的方法。每次遇到新的
relation
,将“引用”更改为引用是的新/最后一个元素。
当不处理
relation
数据时,您可以安全地将数据直接推送到当前引用变量中,它会恰好位于您希望的位置。
代码:(演示)
$ref = [];
$result = &$ref;
foreach ($input as $row) {
if (key($row) !== 'relation') { // populate current level
$ref[] = $row;
continue;
}
if ($ref) { // not the first relation encountered
$ref = &$ref[];
}
$ref = $row; // store relation
}
var_export($result);
你说得对,递归是个好方法。首先,我建议按原样保留原始数组,这样您就不必考虑在处理它时会经历的各种修改。要将其部分标记为已处理,您可以使用索引(如您的
target_index
参数所建议的那样)或将数组的切片传递给递归调用。
我认为你很接近,你只需要在函数末尾对数组的其余部分做一些事情(如果有更多的元素要处理)。