0

Hi i would like to ask if there is any good way to make Nested Array from few strings like in example but when i add NEW STRING it should append

it looks like some kind of tree

String

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

into

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

new String

TEXT1|||AAA222|||AAA333

mew array with old one

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

string is generated from this array indexes are levels in "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)
5
  • can you use JSON instead? Commented Jun 19, 2018 at 4:13
  • yea if i can convert result to array with this form Commented Jun 19, 2018 at 4:15
  • 1
    My question is how do you generate your strings? Why not generate JSON instead. {text1: {text2: {text3: null}, AAA222: {AAA333: null}}} Commented Jun 19, 2018 at 4:16
  • string is generated from array with objects [OBJECT[DATATEXT] OBJECT2[DATATEXT]] Commented Jun 19, 2018 at 4:24
  • how about json_encode($myArray); ? Commented Jun 19, 2018 at 4:48

1 Answer 1

3

This is what I came up with:

//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));
Sign up to request clarification or add additional context in comments.

2 Comments

perfect solution :)
perfect solution, love it, thanks you helped so much

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.