Reputation: 525
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)
Upvotes: 0
Views: 72
Reputation: 151
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));
Upvotes: 3