我有以下字符串: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是一個任意的例子。 –