递归删除数组键前缀

时间:2018-01-12 11:53:05

标签: php arrays recursion

我有一个以下格式的数组(每个子数组都有父键作为前缀):

$input = array(
    'seo_text' => array(
        'seo_text_title'       => '',
        'seo_text_description' => '',
        'seo_text_button'      => array(
            'seo_text_button_text' => '',
            'seo_text_button_url'  => '',
            'seo_text_button_new_tab_enabled' => '',
        ),
    ),
);

我想将其转换为以下格式:

$input = array(
    'seo_text' => array(
        'title'       => '',
        'description' => '',
        'button'      => array(
            'text' => '',
            'url'  => '',
            'new_tab_enabled' => '',
        ),
    ),
);

我试图写一个递归函数,但它没有像它假设的那样工作。

3 个答案:

答案 0 :(得分:4)

解决方案:

function removeKeyPrefix(array $array, string $prefix = ''): array
{
    $newArray = [];
    $prefixLength = strlen($prefix);

    foreach ($array as $key => $value) {
        if (substr($key, 0, $prefixLength) === $prefix) {
            $newKey = substr($key, $prefixLength);
        } else {
            $newKey = $key;
        }

        $newArray[$newKey] = is_array($value) ? removeKeyPrefix($value, $key.'_') : $value;
    }

    return $newArray;
}

$input = removeKeyPrefix($input);

Online demo on 3v4l

答案 1 :(得分:2)

function sanitizeKeys(array $items, $previousKey = '') : array
{
    $previousKey .= "_";

    return array_reduce(
        array_keys($items),
        function($result, $key) use ($previousKey, $items) {
            $newKey = (0 === strpos($key, $previousKey)) ? substr_replace($key, '', 0, strlen($previousKey)) : $key;

            $result[$newKey] = is_array($items[$key]) ? sanitizeKeys($items[$key], $key) : $items[$key];

            return $result;
        }, []
    );
};

sanitizeKeys($input);

答案 2 :(得分:1)

创建一个函数来更改slug中的最后一次出现

function fun($array,$slug){
  foreach($array as $key=>$val){
    $last = end(explode($slug,$key));

    if(is_array($val)){
      $val = fun($val,$key."_");  
    }
    $array[$last] = $val;
    unset($array[$key]);
  }
  return $array;
}
$input["seo_text"] = fun($input["seo_text"],"seo_text_");
print_r($input);

现场演示:https://eval.in/934155

输出

Array
(
    [seo_text] => Array
        (
            [title] => 
            [description] => 
            [button] => Array
                (
                    [text] => 
                    [url] => 
                    [new_tab_enabled] => 
                )

        )

)

如果您在第二级有很多元素,请使用foreach来调用下面的函数

foreach($input as $key=>$val){
  $input[$key] = fun($val,$key."_");
}
print_r($input);

https://eval.in/934156