本文介绍了用两个数组创建多数组php的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个相同的数组,例如var_dump时:
I have two arrays same like when 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}]'
现在,我想下面的结果相同:
Now, i want to result same below:
$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'
感谢帮助!
推荐答案
我认为应该这样做:
// 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()
?)。如果您这样做:
It looks like $arr2
came from improperly parsing JSON by hand (maybe using preg_split()
?). If you do:
$arr2 = json_decode($json_string);
然后,您应该可以用以下方式获得结果:
then you should be able to get your result with just:
$result = array_combine($arr1, $arr2);
这篇关于用两个数组创建多数组php的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!