我有这个字符串:test1__test2__test3__test4__test5__test6=value
可以有任意数量的测试密钥。
我想写一个可以把上面的字符串转换成数组的函数
$data[test1][test2][test3][test4][test5][test6] = "value";这个是可能的吗?
发布于 2011-06-20 21:58:36
$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;
}发布于 2011-06-20 21:58:35
是的,这是可能的:
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;参考:list、explode、=&、is_array、array_pop
发布于 2011-06-20 21:59:26
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));https://stackoverflow.com/questions/6412280
复制相似问题