我有两个与var_dump相同的数组:
$arr1 = array (size=2)
0 => string '10:2'
1 => string '10:1'
$arr2 = array (size=2)
0 => string '[{username:userA,email:userA@gmail.com'
1 => string 'username:userB,email:userB@gmail.com}]'
现在,我想在下面得到相同结果:
$result = array (size=2)
'10:2' =>
array (size=2)
'username' => string 'userA'
'email' => string 'userA@gmail.com'
'10:1' =>
array (size=2)
'username' => string 'userB'
'email' => string 'userB@gmail.com'
感谢您的帮助!
答案 0 :(得分:1)
我认为应该这样做:
// Turn string "key1:val1,key2,val2,..." into associative array.
function str_to_assoc($str) {
$str = str_replace(array('[{', '}]'), '', $str); // Remove extranous garbage
$arr = explode(',', $str);
$res = array();
foreach ($arr as $keyvalue) {
list($key, $value) = explode(':', $keyvalue);
$res[$key] = $value;
}
return $res;
$result = array_combine($arr1, array_map('str_to_assoc', $arr2));
看起来$arr2
来自于手动不正确地解析JSON(可能使用preg_split()
?)。如果你这样做:
$arr2 = json_decode($json_string);
然后你应该能够得到你的结果:
$result = array_combine($arr1, $arr2);