如何从关键元素获取层次结构并基于此创建新元素 - PHP

How to get hyrarchy from key elements and create new elements based on that - PHP

我有一个很大的数组,我会尝试用小例子来解释这个问题:

输入:

Array ( 
[alert:accountDisabled:heading] => XYZ 
[alert:accountDisabled:message] => XYZ
[alert:accountExpired:heading] => XYZ 
[alert:accountExpired:message] => XYZ
[alert:errorResponse:heading] => XYZ 
[button:back] => XYZ 

)

我需要得到的是:

array() { 
    ["alert"]=> array(7) { 
        ["accountDisabled"]=> array(2) { 
            ["heading"]=> string(3) "XYZ" 
            ["message"]=> string(3) "XYZ" } 
       ["accountExpired"]=> array(2) { 
           ["heading"]=> string(3) "XYZ" 
           ["message"]=> string(3) "XYZ" } 
      ["clientError"]=> array(2) { 
          ["heading"]=> string(3) "XYZ" 
          ["message"]=> string(3) "XYZ" } 
      ["errorResponse"]=> array(1) { 
          ["heading"]=> string(3) "XYZ" } 
 }
 ["button"]=> array(1) { 
     ["back"]=> string(3) "XYZ"
 }

正如我所说,这是一个非常小的例子,但重点是从数组一的键中获取层次结构,层次结构除以键中的这个字符 :

我检查了那些看起来与此类似的问题,但它们根本没有帮助

Using a string path to set nested array data

所以请仔细阅读我的问题描述。 我尝试将它用于每个循环,并且成功地将元素从键中划分为一个元素,但我不确定我需要在哪里存储下一个元素的层次结构值,有什么想法吗?

$input = [
    'alert:accountDisabled:heading' => 'XYZ_1',
    'alert:accountDisabled:message' => 'XYZ_2',
    'alert:accountExpired:heading'  => 'XYZ_3',
    'alert:accountExpired:message'  => 'XYZ_4',
    'alert:errorResponse:heading'   => 'XYZ_5',
    'button:back'                   => 'XYZ_6'
];

$results = [];

foreach ($input as $key => $value) {
  $arr = explode(':', $key);
  $result = $value;
  for ($i = count($arr) - 1; $i >= 0; $i--) {
    $result = [ $arr[$i] => $result ];
  }
  $results[] = $result;
}

$result = array_merge_recursive(...$results);

print_r($result);

输出:

Array
(
    [alert] => Array
        (
            [accountDisabled] => Array
                (
                    [heading] => XYZ_1
                    [message] => XYZ_2
                )

            [accountExpired] => Array
                (
                    [heading] => XYZ_3
                    [message] => XYZ_4
                )

            [errorResponse] => Array
                (
                    [heading] => XYZ_5
                )

        )

    [button] => Array
        (
            [back] => XYZ_6
        )

)

根据Lukas.j回答,你可以使用这个函数:

function parsePath($array, $separator = ':'){
    $result = [];
    foreach($array as $key => $value){
       if(strpos($key, $separator) !== FALSE){
           $keys = explode($separator, $key);
           $inner_result = $value;
           foreach (array_reverse($keys) as $valueAsKey) $inner_result = [$valueAsKey => $inner_result];
           $result[] = $inner_result;
       }
    }
    return array_merge_recursive(...$result);
}