将字符串转换为数组

时间:2011-06-20 13:51:53

标签: php multidimensional-array

我有这个字符串:test1__test2__test3__test4__test5__test6=value

可以有任意数量的测试密钥。

我想编写一个可以将上面的字符串转换为数组的函数

$data[test1][test2][test3][test4][test5][test6] = "value";

这可能吗?

5 个答案:

答案 0 :(得分:3)

是的,有可能:

list($keys, $value) = explode('=', $str);
$keys = explode('__', $keys);

$t = &$data;
$last = array_pop($keys);

foreach($keys as $key) {
    if(!isset($t[$key]) || !is_array($t[$key])) {
        // will override non array values if present
        $t[$key] = array();
    }
    $t = &$t[$key];
}

$t[$last] = $value;

DEMO

参考listexplode=&is_arrayarray_pop

答案 1 :(得分:3)

function special_explode($string) {
  $keyval = explode('=', $string);
  $keys = explode('__', $keyval[0]);
  $result = array();

  //$last is a reference to the latest inserted element                         
  $last =& $result;
  foreach($keys as $k) {
    $last[$k] = array();
    //Move $last                                                                
    $last =& $last[$k];
  }

  //Set value                                                                   
  $last = $keyval[1];
  return $result;
}

//Test code:
$string = 'test1__test2__test3__test4__test5__test6=value';
print_r(special_explode($string));

答案 2 :(得分:2)

$data = array();

// Supposing you have multiple strings to analyse...
foreach ($strings as $string) {
    // Split at '=' to separate key and value parts.
    list($key, $value) = explode("=", $string);

    // Current storage destination is the root data array.
    $current =& $data;

    // Split by '__' and remove the last part
    $parts = explode("__", $key);
    $last_part = array_pop($parts);

    // Create nested arrays for each remaining part.
    foreach ($parts as $part)
    {
        if (!array_key_exists($part, $current) || !is_array($current[$part])) {
            $current[$part] = array();
        }
        $current =& $current[$part];
    }

    // $current is now the deepest array ($data['test1']['test2'][...]['test5']).
    // Assign the value to his array, using the last part ('test6') as key.
    $current[$last_part] = $value;
}

答案 3 :(得分:1)

$str = ...;
eval( str_replace('__', '][', 
preg_replace('/^(.*)=(.*)$/', '\$data[$1]=\'$2\';', $str)) );

更简单的方法,假设$str是可信任的数据

答案 4 :(得分:0)

我想是......

$string = "test1__test2__test3__test4__test5__test6=value";
$values = explode('=',$string);
$indexes = explode('__',$values[0]);
$data[$indexes[0]][$indexes[1]][$indexes[2]][$indexes[3]][$indexes[4]][$indexes[5]] = $values[1];