Thought this was an easy one, but after Googling around for awhile, I've come up short. I need to combine two PHP arrays while ignoring the keys:
认为这是一个简单的,但谷歌搜索了一段时间后,我已经做空了。我需要组合两个PHP数组而忽略键:
array(
0 => 'Word 1',
1 => 'Word 2'
)
array(
0 => 'Word 3',
1 => 'Word 4',
2 => 'Word 5'
)
Result should be:
结果应该是:
array(
0 => 'Word 1',
1 => 'Word 2',
2 => 'Word 3',
3 => 'Word 4',
4 => 'Word 5'
)
Tried array_merge
but that replaces duplicate keys. array_combine
won't work because it requires the same numer of elements in both array.
尝试使用array_merge但替换了重复的键。 array_combine不起作用,因为它需要两个数组中相同数量的元素。
2 个解决方案
#1
10
array_merge
should do the trick. If it doesn't, meaning your keys are probably not numeric. Try converting them into plain values based arrays first, then merge them.
array_merge应该做的伎俩。如果没有,则意味着您的密钥可能不是数字。首先尝试将它们转换为基于普通值的数组,然后合并它们。
array_merge(array_values($a), array_values($b))
Should do the trick.
应该做的伎俩。
Sample: https://3v4l.org/chuXV
示例:https://3v4l.org/chuXV
array_values: http://php.net/manual/en/function.array-values.php
array_values:http://php.net/manual/en/function.array-values.php
#2
-1
//Try using two for loops to copy the data over to a third array like this.
<?php
$a1 = array(
0 => 'w1',
1 => 'w2'
);
$a2 = array(
0 => 'w3',
1 => 'w4',
2 => 'w5'
);
$counter = 0;
for($i = 0; $i < count($a1); $i++){
$a3[$counter] = $a1[$i];
$counter++;
}
for($i = 0; $i < count($a2); $i++){
$a3[$counter] = $a2[$i];
$counter++;
}
print_r($a3);
?>
#1
10
array_merge
should do the trick. If it doesn't, meaning your keys are probably not numeric. Try converting them into plain values based arrays first, then merge them.
array_merge应该做的伎俩。如果没有,则意味着您的密钥可能不是数字。首先尝试将它们转换为基于普通值的数组,然后合并它们。
array_merge(array_values($a), array_values($b))
Should do the trick.
应该做的伎俩。
Sample: https://3v4l.org/chuXV
示例:https://3v4l.org/chuXV
array_values: http://php.net/manual/en/function.array-values.php
array_values:http://php.net/manual/en/function.array-values.php
#2
-1
//Try using two for loops to copy the data over to a third array like this.
<?php
$a1 = array(
0 => 'w1',
1 => 'w2'
);
$a2 = array(
0 => 'w3',
1 => 'w4',
2 => 'w5'
);
$counter = 0;
for($i = 0; $i < count($a1); $i++){
$a3[$counter] = $a1[$i];
$counter++;
}
for($i = 0; $i < count($a2); $i++){
$a3[$counter] = $a2[$i];
$counter++;
}
print_r($a3);
?>