如何按顺序组合顺序数组和关联数组:
示例:
$sequentialArray = [123, 'Jonh'];
$associativeArray = ['ID' => '321', 'name' => 'Paul', 'lastName' => 'Wood'];
mergeArray($sequentialArray, $associativeArray);
返回:
Array
(
[ID] => 123
[name] => Jonh
[lastName] => Wood
)
答案 0 :(得分:1)
考虑一下:
<?php
header('Content-Type: text/plain; charset=utf-8');
$sequentialArray = [ 123, 'Jonh'];
$associativeArray = ['ID' => '321', 'name' => 'Paul', 'lastName' => 'Wood'];
$keys = array_slice(
array_keys($associativeArray),
0,
count($sequentialArray)
);
print_r(
array_merge(
$associativeArray,
array_combine($keys, $sequentialArray)
)
);
?>
<强>输出:强>
Array
(
[ID] => 123
[name] => Jonh
[lastName] => Wood
)
进一步阅读: Array functions @ php.net。
<强> UPDv1:强>
这是功能:
<?php
header('Content-Type: text/plain; charset=utf-8');
$sequentialArray = [ 123, 'Jonh'];
$associativeArray = ['ID' => '321', 'name' => 'Paul', 'lastName' => 'Wood'];
function mergeArray($assoc, $seq){
$keys = array_slice(array_keys($assoc), 0, count($seq));
return array_merge($assoc, array_combine($keys, $seq));
}
print_r(mergeArray($associativeArray, $sequentialArray));
?>
答案 1 :(得分:1)
试试这个
$sequentialArray = [123, 'Jonh'];
$associativeArray = ['ID' => '321', 'name' => 'Paul', 'lastName' => 'Wood'];
$newArr = array();
$i = 0;
foreach($associativeArray as $key=>$val){
if(isset($sequentialArray[$i])){
$newArr[$key] = $sequentialArray[$i];
}else{
$newArr[$key] = $val;
}
$i++;
}
<强>输出:强>
Array
(
[ID] => 123
[name] => Jonh
[lastName] => Wood
)
print_r($newArr);