我這個自定義功能這方面的工作。感謝Trey在「array combine three or more arrays with php」的原始功能,您可以根據您的需要添加任意數量的陣列。
功能#1:
function arrayMerge() {
$args = func_get_args();
$idx1 = range(1, count($args[1]));
$idx2 = range(1, count($args[2]));
foreach($args as $key => $array) {
$vkey = array_shift($idx2);
foreach($array as $akey => $val) {
$result[$idx1[$akey]][$vkey] = $val;
} #foreach
} #foreach
return $result;
} #arrayMerge
示例陣列使用:
$codes = array('US', 'GB', 'AE');
$names = array('United States', 'United Kingdom', 'United Arab Emirates');
$population = array('307,212,123', '61,113,205', '4,798,491');
$area = array('9,826,675', '243,610', '83,600');
功能用途:
print_r(arrayMerge($codes, $names, $population, $area));
我已經添加了兩個自動數字索引的,並從1個instad的開始0.
實施例陣列輸出:
Array
(
[1] => Array
(
[1] => US
[2] => United States
[3] => 307,212,123
[4] => 9,826,675
)
[2] => Array
(
[1] => GB
[2] => United Kingdom
[3] => 61,113,205
[4] => 243,610
)
[3] => Array
(
[1] => AE
[2] => United Arab Emirates
[3] => 4,798,491
[4] => 83,600
)
)
下面是一個更該自定義使用子密鑰,在這一個我添加一個自動nameric索引和從1而不是0開始。
功能#2:
function arrayMerge2() {
$args = func_get_args();
$idx = range(1, count($args[1]));
$keys = array_shift($args);
foreach($args as $key => $array) {
$vkey = array_shift($keys);
foreach($array as $akey => $val) {
$result[$idx[$akey]][$vkey] = $val;
} #foreach
} #foreach
return $result;
} #arrayMerge2
實例陣列被使用:
$codes = array('US', 'GB', 'AE');
$names = array('United States', 'United Kingdom', 'United Arab Emirates');
$population = array('307,212,123', '61,113,205', '4,798,491');
$area = array('9,826,675', '243,610', '83,600');
$keys = array('code', 'name', 'popu', 'area');
功能用途:
print_r(arrayMerge2($keys, $codes, $names, $population, $area));
例陣列輸出:
Array
(
[1] => Array
(
[code] => US
[name] => United States
[popu] => 307,212,123
[area] => 9,826,675
)
[2] => Array
(
[code] => GB
[name] => United Kingdom
[popu] => 61,113,205
[area] => 243,610
)
[3] => Array
(
[code] => AE
[name] => United Arab Emirates
[popu] => 4,798,491
[area] => 83,600
)
)
噢,這個功能也支持空值數組 :-)
我希望這可以幫助另外一個人需要simular陣列配置。
你已經試過了什麼嗎?你在哪裏陷入特定? – PeeHaa
什麼是源數組? –
請參閱上文,我已編輯帖子。 – Tux