PHP字符串到嵌套/多维数组

时间:2011-12-30 05:06:21

标签: php arrays parsing multidimensional-array tree

我有这个例子php string:

  

$ string =“@ [item_1] [door] @ [mozart] [grass] = yes @ [mozart] [green] = no @ [mozart] [human] @ [blue] [movie] = yes @ [ item_1] [beat] = yes @ [item_1] [音乐] =不   “;

现在$ string只是为了方便查看:

  
      
  1. @ [item_1] [门]
      
        
    • @ [mozart] [grass] =是
    •   
    • @ [mozart] [green] =否
    •   
    • @ [mozart] [human]

    •   
      •   
      • @ [蓝色] [电影] =是

      •   
    •   
    • @ [item_1] [beat] =是
    •   
    • @ [item_1] [音乐] =否
    •   
  2.   

我想知道如何获取此字符串(或此样式后的其他字符串)并转换为如下所示的数组:

Array
(
    [item_1] => Array
        (
            [door] => Array
                (
                    [mozart] => Array
                        (
                            [grass] => yes
                            [green] => no
                            [human] => Array
                                (
                                    [blue] => Array
                                        (
                                            [movie] => yes
                                        )
                                )
                        )
                )
            [beat] => yes
            [music] => no
        )
)

我尝试了什么

我尝试使用和递归函数来创建嵌套数组但我无法访问递归函数中的数组指针(在深层次)..不知道为什么..也许是错误的补丁回答。 谢谢,

1 个答案:

答案 0 :(得分:3)

好的,我希望你仍然需要这个,因为我浪费了更多的时间,而不是管理这个权利:)

基本上,我的方法是首先将字符串操作为[set] [of] [keys] = value格式,然后遍历键串并将它们与最后一组键进行比较以创建正确的键层次结构。我使用了eval,因为它更容易,但如果你不能在代码中看到这个功能,你可以写一个替换函数:

//FIRST WE GET THE STRING INTO EASIER TO WORK WITH CHUNKS
$original_string = "@[item_1][door] @[mozart][grass] = yes @[mozart][green] = no @[mozart][human] @[blue][movie]=yes @[item_1][beat] = yes @[item_1][music] = no ";
$cleaned_string = str_replace('] @[','][',$original_string);
/* This results in clusters of keys that equal a value:
@[item_1][door][mozart][grass] = yes @[mozart][green] = no @[mozart][human][blue][movie]=yes @[item_1][beat] = yes @[item_1][music] = no 

OR (with line breaks for clarity):

@[item_1][door][mozart][grass] = yes 
@[mozart][green] = no 
@[mozart][human][blue][movie]=yes 
@[item_1][beat] = yes 
@[item_1][music] = no */

//break it up into an array:
$elements = explode('@',$cleaned_string);

//create a variable to compare the last string to
$last_keys = "";
//and another that will serve as our final array
$array_of_arrays = array();
//now loop through each [item_1][door][mozart][grass] = yes,[mozart][green] = no, etc
foreach($elements as $element){
    if ($element==""){continue;} //skip the first empty item

    //break the string into [0] = group of keys and [1] the value that terminates the string 
    //so [item_1][door][mozart][grass] = yes BECOMES [item_1][door][mozart][grass], AND yes
    $pieces = explode('=',str_replace(array('[',']'),array("['","']"),trim($element))); 
    //now compare this set of keys to the last set of keys, and if they overlap merge them into a single key string
    $clean_keys = combine_key_strings($pieces[0],$last_keys);
    //set the new key string the value for the next comparison
    $last_keys = $clean_keys;
    //and (ugly, I know) we use an eval to convert "[item_1][door][mozart][grass]='yes'" into a properly keyed array
    eval("\$array_of_arrays".$clean_keys." = '".trim($pieces[1])."';");
}

//now dump the contents
print_r($array_of_arrays);


//THIS FUNCTION COMPA
function combine_key_strings($new,$old){
    //get the key that starts the newer string
    $new_keys = explode('][',$new);
    $first_key = $new_keys[0].']';

    //see if it appears in the last string
    $last_occurance = strrpos ($old,$first_key);
    //if so, merge the two strings to create the full array keystring
    if (is_int($last_occurance)){
        return substr($old,0,$last_occurance).$new;
    }
    return $new;
}

这应该吐出你正确嵌套的数组:

Array
(
    [item_1] => Array
        (
            [door] => Array
                (
                    [mozart] => Array
                        (
                            [grass] => yes
                            [green] => no
                            [human] => Array
                                (
                                    [blue] => Array
                                        (
                                            [movie] => yes
                                        )

                                )

                        )

                )

            [beat] => yes
            [music] => no
        )

)

晚安!