【问题标题】:PHP string to nested / multidimensional arrayPHP字符串到嵌套/多维数组
【发布时间】:2011-12-30 05:06:21
【问题描述】:

我有这个示例 php 字符串:

$string = "@[item_1][door] @[mozart][grass] = yes @[mozart][green] = no @[mozart][human] @[blue][movie]=yes @[ item_1][beat] = 是 @[item_1][music] = 否 ";

现在 $string 标识为便于查看:

  1. @[item_1][门]
    • @[莫扎特][草] = 是
    • @[莫扎特][绿色] = 没有
    • @[莫扎特][人类]

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

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

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

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

我尝试了什么

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

【问题讨论】:

  • 你可以展示你的递归函数。如果您使用引用,则可能需要保留它们的列表,因为您正在使用这种方法进出子数组。
  • 如何从原始字符串逻辑上确定 blue 是 Human 内部的一个数组?如果您不能定义一个相当简单的规则来确定这一点,那么编码将很难或不可能。
  • 为什么不坚持使用 XML 或 JSON?
  • 您的字符串中的格式不明确。例如,第 1 行缩进,而第 6 行 (@[item_1][beat] = yes) 缩进 1 级。这里没有明确的格式。
  • 字符串有一个格式,我现在已经有一个处理它的函数 - gist.github.com/1553533 - 现在的问题是我正在尝试将它转换为 JSON 并详细说明我将在该主题上解释. @马里奥

标签: php arrays parsing multidimensional-array tree


【解决方案1】:

好的,我希望你仍然需要这个,因为我浪费的时间比我想管理的要多:)

基本上,我的方法是首先将字符串操作为 [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
        )

)

晚安!

【讨论】:

  • 太好了!非常感谢@ben-d!这是一个非常大的问题!很棒的功能!谢谢!
  • 请记住我对 eval() 调用的警告...如果数据有可能复制 php 函数调用(特别是如果任何数据由第三方设置)您可能会面临 php 注入风险,在这种情况下,您需要编写一个自定义函数来处理此过程(生成一个数组并递归地将其与主数组合并)。祝你好运!
猜你喜欢
  • 2017-07-08
  • 2014-07-16
  • 1970-01-01
  • 2019-02-06
  • 1970-01-01
  • 1970-01-01
  • 2018-06-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多