微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

php – 从字符串追加到数组

我有一个名为$data的数组,需要使用来自ajax调用的数据进行更新.

通过ajax调用发送了两个变量(带有示例输入):

sectionDetails:

[111][0][2][0][service_providers][]

服务提供者:

Google

serviceProvider是数据,sectionDetails是serviceProvider应该在$data数组中的数组.

我需要的是$data数组最终:

$data  =   Array
(
[111] => Array
    (
        [0] => Array
            (
                [2] => Array
                    (
                        [0] => Array
                            (
                                [service_providers] => Array 
                                                    (
                                                        [0] = Google
                                                    )
                            )

                    )

            )

    )

)

这样,我可以动态地将数据输入到任何单元格中,然后我可以更新特定的数组(例如$data [111] [0] [2] [0] [service_providers] [0] =“Yahoo”;

然而,$_POST [‘sectionDetails’]是一个问题所在的字符串.

有没有办法将此字符串更改为一个数组,然后可以将其附加到主$data数组(如果在同一部分中存在现有值,则更新该值)?

希望有道理.

解决方法:

如果您创建这样的函数

function setToPath(&$data, $path, $value){
    //$temp will take us deeper into the nested path
    $temp = &$data;

    //notice this preg_split logic is specific to your path Syntax
    $exploded = preg_split("/\]\[/", rtrim(ltrim($path,"["),"]")); 

    // Where $path = '[111][0][2][0][service_providers][]';
    // $exploded = 
    //    Array
    //    (
    //        [0] => 111
    //        [1] => 0
    //        [2] => 2
    //        [3] => 0
    //        [4] => service_providers
    //        [5] => 
    //    )
    foreach($exploded as $key) {
        if ($key != null) {
            $temp = &$temp[$key];
        } else if(!is_array($temp)) {
            //if there's no key, i.e. '[]' create a new array
            $temp = array();
        }
    }
    //if the last index was '[]', this means push into the array
    if($key == null) {
        array_push($temp,$value);
    } else {
        $temp = $value;
    }
    unset($temp);
}

你可以像这样使用它:

setToPath($data, $_POST['sectionDetails'], $_POST['serviceProvider']);

print_r($data)将返回:

Array
(
    [111] => Array
        (
            [0] => Array
                (
                    [2] => Array
                        (
                            [0] => Array
                                (
                                    [service_providers] => Array
                                        (
                                            [0] => Google
                                        )

                                )

                        )

                )

        )

)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐