如何在PHP中通过分隔符将字符串分解为多维数组

时间:2017-07-06 11:30:26

标签: php

我有一个字符串'value1 / value2'。所需的输出是$ _SESSION ['value1'] ['value2']。我尝试使用explode然后使用array_reduce而不是爆炸值,但没有成功。

我的代码看起来像

function set($key, $value){
/* code */
}

set('key1/key2', 'some_text');

所需的输出,如$_SESSION['key1']['key2'] = 'some_text';

key1 / key2不固定,可能是'key1'或'key1 / key2 / key3',依此类推。 任何人都是小提琴,非常值得注意。 感谢

3 个答案:

答案 0 :(得分:2)

通过键路径字符串访问值,就像在原始问题中一样,使用您的原始想法让array_reduce完成工作,如下所示:

$session = ['value1' => [ 'value2' => [ 'value3' => 'there you are!' ]]];
$path = explode('/', 'value1/value2/value3');
$val = array_reduce($path, 
                    function(&$carry, $key) { return $carry[$key];},
                    $session);
echo $val
--> "there you are!"

可以设置值,例如像这样,按照引用路径,根据需要创建数组:

function set($path, $value) {
    $path = explode('/', $path); 
    $key = array_pop($path); 
    $arr = &$_SESSION; 
    foreach($path as $part) {
        // carefull, this might lose values to accommodate
        // the structure wanted with $path
        (isset($arr[$part]) && is_array($arr[$part])) || ($arr[$part] = []); 
        $arr =& $arr[$part];
    } 
    $arr[$key] = $value;
};

答案 1 :(得分:1)

试试这个

<?php 
  session_start();   
  $string  = 'value1/value2';
  $array = explode("/",$string);
  $_SESSION[$array[0]][$array[1]] = "ccccccc";//$_SESSION['value1']['value2']

答案 2 :(得分:1)

对于一般情况(即超过两个部分),您需要迭代这些段,并逐步将索引进一步索引到目标数组中:

<?php
$string = 'value1/value2/value3';

$_SESSION = ['value1' => ['value2' => ['value3' => 'My String']]];

$target = $_SESSION;

foreach (explode('/', $string) as $piece) {
    $target =& $target[$piece];
}

echo $target; // My String