我是阵列新手。希望您能够帮助我。我有2个阵列。让我们说:
数组1 = [[50,60],[70,80]]
阵列2 = [“火”,“海洋”]
数组1索引:数组([0] =>数组([0] => 50 [1] => 60)[1] =>数组 ([0] => 70 [1] => 80))
array 2 index:Array([0] => Fire [1] => Marine)
如何将数组2插入数组1,如下面的输出:
我想要的输出如下:
数组3 = [[“Fire”,50,60],[“Marine”,70,80]]
array 3 index =(Array([0] => Array([0] => Fire [1] => 50 [2] => 60) [1] =>数组([0] =>海洋[1] => 70 [2] => 80))
由于
答案 0 :(得分:2)
array_unshift()将一个或多个元素添加到数组的开头,即子数组中所需的元素。 http://codepad.org/ufRe2qiz
$arr1 = array( array(50, 60), array(70, 80) );
$arr2 = array("Fire", "Marine");
$arr3 = array();
$i = 0;
foreach( $arr1 as $child ){
array_unshift( $child, $arr2[$i] );
$arr3[] = $child;
$i++;
}
print_r( $arr3 );
Array
(
[0] => Array
(
[0] => Fire
[1] => 50
[2] => 60
)
[1] => Array
(
[0] => Marine
[1] => 70
[2] => 80
)
)
答案 1 :(得分:1)
使用array_map()
功能
<强> codepad demo 强>
$array1 = array(array(50,60),array(70,80));
$array2 = array("Fire", "Marine");
function mergebyindex($a, $b){
$temp = array();
$temp[] = $a;
if(is_scalar($b)){
$temp[] = $b;
} else {
foreach($b as $k => $v ){
$temp[] = $v;
}
}
return $temp;
}
echo '<pre>'; print_r(array_map('mergebyindex',$array2, $array1));
答案 2 :(得分:1)
试试此代码
<?php
//original array1
$array1=array(
0=>array(0=>50,1=>60),
1=>array(0=>70,1=>80)
);
//original array2
$array2=array(0=>'Fire',1=>'Marine');
//new array
$array3=array();
foreach($array1 as $key=>$val)
{
$array3[$key]=$val;
array_push($array3[$key],$array2[$key]);
}
print_r($array3);
?>
输出:Array ( [0] => Array ( [0] => 50 [1] => 60 [2] => Fire ) [1] => Array ( [0] => 70 [1] => 80 [2] => Marine ) )
应该尝试一下!!
答案 3 :(得分:0)
我会重新考虑你的编程逻辑,说实话,当你遇到更大规模的任务时(特别是在映射中),这些数组会变得非常混乱。
在PHP中,您可以通过以下方式轻松将事物推送到数组的末尾:
$arr1[] = 'val1';
$arr1[] = 'val2';
同样如下:
$arr1 = array('val1','val2');
如果您不关心数组定位,可以执行以下操作:
$arr2 = array(50,70); //original array
$arr2[] = 'marine';
会给:
$arr2 = array(50,70,'marine');