我有以下字符串:test1__test2__test3__test4__test5__test6=value
将字符串转换为数组
可能有任何数量的测试密钥。
我想写,可以把上面的字符串到一个数组
$data[test1][test2][test3][test4][test5][test6] = "value";
这是可能的功能?
我有以下字符串:test1__test2__test3__test4__test5__test6=value
将字符串转换为数组
可能有任何数量的测试密钥。
我想写,可以把上面的字符串到一个数组
$data[test1][test2][test3][test4][test5][test6] = "value";
这是可能的功能?
$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;
}
谢谢你。我需要分析很多字符串,然后编译一个大数组。 –
我想这是...
$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];
'explode()'不能处理正则表达式,所以'explode('_ +')'不会在'__'上分割。 –
是的,它是可能的:
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;
你应该把'$ t =&$ t [$ key]'放在if语句之外...... –
@费迪南德:谢谢!如果代码太快,会发生这种情况:D;) –
此外,如果'$ key'不在'$ data'中,'is_array($ data [$ key])'会发出警告(甚至错误?)。你的意思是'isset()'? ;) –
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));
$str = ...;
eval(str_replace('__', '][',
preg_replace('/^(.*)=(.*)$/', '\$data[$1]=\'$2\';', $str)));
更简单的方法,假设$str
是可信的数据
您至少应该为引号添加引号。否则,您会收到警告,提示您使用了未定义的常量,并且如果其中一个键恰好是常数名称,您将遇到麻烦。也许你还应该强调**值得信任的**方面... –
同意Ferinand。但否则很好的解决方案这是我看到的'eval'的第一部分代码,我会在自己的项目中接受它8)。 – Slava
似乎有点复杂,为什么你需要为做到这一点? – Tomgrohl
是否总是6项或更多/更少? –
@Salman:“可能有任何数量的测试密钥。” - 我猜6是一个任意的例子。 –