Searching for a way to construct a multidimensional, multilayered, associative Array

末鹿安然 提交于 2021-02-11 14:14:46

问题


So i am running into trouble while iterating through a string and inserting it's chars as index-arrays into a multidimensional,associative array. So basically a bunch of multidimensional arrays in multidimensional arrays in multidimensional arrays..... That is a bit troublesome as i cant do it by hand. I need an automated way to do this with a bunch of strings. The following example will explain it a bit better i think:

//string i want to enter
$string = 'ADAM';
//array i want to end up with
$result = array
              (
                'A'=> array
                 (
                  'D'=>array
                   (
                    'A'=>array
                     (
                      'M'=>array
                        (
                          'result'=>'ADAM'
                        )
                     )
                   )
                 )
               )

my initial approach was just using if-conditions to insert the first Char as Array into the main-array like:

for($i = 0; $i < strlen($string); $i++){
      if($i == 0){
       $array1[$word[$i]] = array();
      }
}

which works pretty well. But then i ran into my Problem: how do i keep track of the current point in the array? Following the if-check i would go for an else-statement that acts when $i is bigger than 0. But if i want to insert the next dimension of array, which would be 'D' in this case, i would need to select $array1['A'], for the next i would need $array1['A']['D'] etc. I wasn't able to find a way yet to do that. The strings i need to get into this array vary from 4-70 chars. Each method i know of only changed the 2nd dimension so i ended up with:

$array1('A'=>array ('A' =>array()));
$array1('A'=>array ('D' =>array()));
$array1('A'=>array ('A' =>array()));
$array1('A'=>array ('M' =>array()));

or illegal offset-errors caused by the indexes being arrays themselves. Maybe my approach here is not possible, but i still thought i might ask in case i missed something.

In a Later stage im looking to use the same array for all strings so i basically use the Chars as nodes.. if 'A' as first char already exists i would then skip that and insert the 2nd char of the next string into the 'A'-Array etc.

Thanks in Advance!


回答1:


You can use a recursive function for this.

function nest(string $str, int $i = 0) {
    return isset($str[$i]) ? [$str[$i] => nest($str, $i + 1)] : ['result' => $str];
}

$result = nest($string);



回答2:


here is a solution for what you are trying to achieve. See a working solution here with comments to explain it's working.

$val = 'ADAM';
$arr = [];
$keys = str_split($val);
$curr = &$arr;
foreach($keys as $key) {
    $curr = &$curr[$key];
}
$curr = ['result' => $val];

print_r($arr);



回答3:


You can use references, so that as you go through the string you add the next character as the key to the array and then set this new entry as the add point for the next operation in the loop...

$string = 'ADAM';
$result = [];
$add = &$result;
for($i = 0; $i < strlen($string); $i++){
    $add = &$add[$string[$i]];
}
$add['result'] = $string;
print_r($result);

Just to show how adding multiple entries would work...

addEntry ( $result, "ADAM");
addEntry ( $result, "ALAN");
addEntry ( $result, "ADAME");

function addEntry ( &$result, string $newValue )  {
    for($i = 0; $i < strlen($newValue); $i++){
        $result = &$result[$newValue[$i]];
    }
    $result['result'] = $newValue;
}

results in...

Array
(
    [A] => Array
        (
            [D] => Array
                (
                    [A] => Array
                        (
                            [M] => Array
                                (
                                    [result] => ADAM
                                    [E] => Array
                                        (
                                            [result] => ADAME
                                        )

                                )

                        )

                )

            [L] => Array
                (
                    [A] => Array
                        (
                            [N] => Array
                                (
                                    [result] => ALAN
                                )

                        )

                )

        )

)


来源:https://stackoverflow.com/questions/60567240/searching-for-a-way-to-construct-a-multidimensional-multilayered-associative-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!