将字符串转换为数组



我有这个字符串:test1__test2__test3__test4__test5__test6=value

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

我想写一个函数,可以把上面的字符串变成数组

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

这可能吗?

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));

有可能:

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;

演示

参考listexplode=&is_arrayarray_pop

$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;
}
$str = ...;
eval( str_replace('__', '][', 
preg_replace('/^(.*)=(.*)$/', '$data[$1]='$2';', $str)) );

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

我想是…

$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];

相关内容

  • 没有找到相关文章

最新更新