我有一个这样的输入数组
$input = array(
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"
),
);
我想要达到的输出是这个
$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;
}
我的做法正确吗?
你说得对,递归是个好方法。首先,我建议按原样保留原始数组,这样您就不必考虑在处理它时会经历的各种修改。要将其部分标记为已处理,您可以使用索引(如您的
target_index
参数所建议的那样)或将数组的切片传递给递归调用。
我认为你很接近,你只需要在函数末尾对数组的其余部分做一些事情(如果有更多的元素要处理)。