請問數組合并有關問題

來源:互聯網
上載者:User
請教數組合并問題
本帖最後由 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

只研究代碼不研究其他
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.