2010-12-11 34 views
2

如何將兩個關聯數組連接起來? 對於exapmle: 數組1PHP中的數組連接問題

$numbers = array(); 
$numbers['id'] = 4; 
$numbers['num'] = 391; 
$numbers['rupees'] = 'Adeel'; 

數組2

$numbers1 = array(); 
$numbers1['id'] = 5; 
$numbers1['num'] = 392; 
$numbers1['name'] = 'shah'; 

結果應該是這樣的

id num name 
4 391 Adeel 
5 392 waqar 

我應該做的???

+3

連接如何?按順序添加所有現有密鑰,甚至重複?用另一箇中的密鑰覆蓋一個密鑰? – 2010-12-11 12:59:48

+0

你能舉一個你想看到結果的例子嗎? – ircmaxell 2010-12-11 13:18:10

+0

是Ignacio,用另一箇中的鍵覆蓋鍵中的一個...... – Adeel 2010-12-11 13:30:05

回答

4

從你的例子中,你並不需要將它們串聯。你需要將它們放在同一陣列中:

$numbers = array(); 
$numbers['id'] = 4; 
$numbers['num'] = 391; 
$numbers['rupees'] = 'Adeel'; 

$numbers1 = array(); 
$numbers1['id'] = 5; 
$numbers1['num'] = 392; 
$numbers1['name'] = 'shah'; 

$all[] = $numbers; 
$all[] = $numbers1; 

這樣,您將得到的東西與你當你從數據庫中獲取一致。

+0

可能有理由將'id'字段保留爲'$ all'上的鍵。 – Orbling 2010-12-11 13:48:54

+0

@Orbling我不同意。 – 2010-12-11 13:49:58

+0

@Alin Purcaru:很好,但很好奇爲什麼不呢? – Orbling 2010-12-11 13:54:26

2

使用array_merge()

$con_array = array_merge ($numbers, $number1); 

這會給你$con_array

Array 
(
    [id] => 4 
    [num] => 391 
    [rupees] => Adeel 
    [name] => Adeel 
) 
+0

請注意更新的問題 - 它不是'array_merge()'候選人。 – Orbling 2010-12-11 13:47:25