請教數組合并問題
本帖最後由 lumengabc 於 2014-01-19 20:13:57 編輯
$a = array('sh'=>500,'bj'=>100, 'jx'=>20);
$b = array('bj'=>5, 'cq'=>50, 'sh'=>0);
//要求合并$a和$b, 得到結果:
$c =array(
'sh'=>array(500,0),
'bj'=>array(100,0),
'jx'=>array(20,0),
'cq'=>array(0,50),
);
即還是按數組$a的順序排序,將$b的值疊加到對應$a
------解決方案--------------------
$a = array('sh'=>500,'bj'=>100, 'jx'=>20);
$b = array('bj'=>5, 'cq'=>50, 'sh'=>0);
$keys = array_keys(array_merge($a,$b));
foreach($keys as $k){
$ar[$k]=array($a[$k] ? $a[$k] : 0 , $b[$k] ? $b[$k] : 0);
}
print_r($ar);
Array
(
[sh] => Array
(
[0] => 500
[1] => 0
)
[bj] => Array
(
[0] => 100
[1] => 5
)
[jx] => Array
(
[0] => 20
[1] => 0
)
[cq] => Array
(
[0] => 0
[1] => 50
)
)
------解決方案--------------------
$a = array('sh' => 500, 'bj' => 100, 'jx' => 20);
$b = array('bj' => 5, 'cq' => 50, 'sh' => 0);
var_dump(array_merge_recursive($a+array_fill_keys(array_keys(array_merge($a, $b)), '0'), $b));
引用:
$a = array('sh'=>500,'bj'=>100, 'jx'=>20);
$b = array('bj'=>5, 'cq'=>50, 'sh'=>0);
//要求合并$a和$b, 得到結果:
$c =array(
'sh'=>array(500,0),
'bj'=>array(100,0),
'jx'=>array(20,0),
'cq'=>array(0,50),
);
即還是按數組$a的順序排序,將$b的值疊加到對應$a
高效能時版主會代碼會出現BUG我不知道你的資料量有多大
可以分別運行測試我本地是php5.5.6所有版主代碼稍微改動了下否則程式跑不起來(關閉錯誤輸出也不行php版本問題)
$pagestartime = microtime();
$b = $a = range(0, 100000);
array_merge_recursive($a + array_fill_keys(array_keys(array_merge($a, $b)), '0'), $b);
$pageendtime = microtime();
$starttime = explode(" ", $pagestartime);
$endtime = explode(" ", $pageendtime);
$totaltime = $endtime[0] - $starttime[0] + $endtime[1] - $starttime[1];
$timecost = sprintf("%s", $totaltime);
var_dump($timecost);
$pagestartime = microtime();
$b = $a = range(0, 100000);
$keys = array_keys(array_merge($a, $b));
$ar=array();
foreach ($keys as $k) {
$ar[$k] = array(isset($a[$k]) ? $a[$k] : 0, isset($a[$k]) ? $b[$k] : 0);
}
$pageendtime = microtime();
$starttime = explode(" ", $pagestartime);
$endtime = explode(" ", $pageendtime);
$totaltime = $endtime[0] - $starttime[0] + $endtime[1] - $starttime[1];
$timecost = sprintf("%s", $totaltime);
var_dump($timecost);
1w條資料時
版主代碼
My Code
10w條資料時
版主代碼
My Code
100w資料庫時
都會出現
Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 32 bytes)錯誤
memory_limit可解決此問題
我本地memory_limit = 128M
版主代碼 9.4w
My Code 22w
只研究代碼不研究其他