字符串到嵌套数组

时间:2018-06-19 03:46:37

标签: php

您好我想问一下是否有任何好方法可以从几个字符串中制作嵌套数组,但是当我添加新STRING时它应该附加

它看起来像某种树

字符串

  

TEXT1 ||| TEXT2 ||| TEXT3 ....

进入

  

[TEXT1 => [TEXT2 => [TEXT3]]]

new String

  

TEXT1 ||| ||| AAA222 AAA333

旧的阵列

  

[TEXT1 => [TEXT2 => [TEXT3 => null],AAA222 => [AAA333 => null]]]

字符串是从这个数组生成的索引是" tree"

中的级别
array (size=5)
0 => 
array (size=2)
  'a' => string 'Motoryzacja' (length=11)
  'b' => string '' (length=0)
1 => 
array (size=2)
  'a' => string 'Części samochodowe' (length=20)
  'b' => string '' (length=0)
2 => 
array (size=2)
  'a' => string 'Części karoserii' (length=18)
  'b' => string '' (length=0)
3 => 
array (size=2)
  'a' => string 'Błotniki' (length=9)
  'b' => string '' (length=0)
4 => 
array (size=2)
  'a' => string 'Maski' (length=5)
  'b' => string '' (length=0)

1 个答案:

答案 0 :(得分:3)

这就是我提出的:

//recursive function to build the array
function buildArray(Array $input, $output=[]){
  $len = count($input);
  if ($len > 0){
    $key = array_shift($input);
    //if there is more in the array, then we need to continue building our array
    if (($len - 1) > 0){
      $output[$key] = buildArray($input,$output);
    }
    else {
      $output[$key] = NULL;
    }
  }
  return $output;
}
//converts string input with ||| delimiter into nested Array
function stringToArray(String $input){
  $arr = explode('|||', $input);
  $output = buildArray($arr);
  return $output;
}

$arr = stringToArray("TEXT1|||TEXT2|||TEXT3");
$arr2 = stringToArray("TEXT1|||AAA222|||AAA333");
var_dump(array_merge_recursive($arr,$arr2));