0

i am new to array. Hope you can help me. i have 2 array. Let say:

array 1 = [[50,60],[70,80]]

array 2 = ["Fire", "Marine"]

array 1 index : Array([0]=>Array ([0]=>50 [1]=>60) [1]=>Array ([0]=>70 [1]=>80))

array 2 index : Array ([0]=> Fire [1]=>Marine)

How i can insert array 2 into array 1 like output below :

Output that i want like below:

array 3 = [["Fire",50,60],["Marine",70,80]]

array 3 index = (Array([0]=>Array ([0]=>Fire [1]=>50 [2]=>60) [1]=>Array ([0]=>Marine [1]=>70 [2]=>80))

Thanks

4

4 回答 4

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
    )

)
于 2013-10-23T04:12:18.473 回答
1

使用array_map()功能

键盘演示

$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));
于 2013-10-23T04:03:41.107 回答
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 ) )

它应该工作试一试!

于 2013-10-23T04:15:02.267 回答
0

老实说,我会重新考虑你的编程逻辑,当你遇到更大规模的任务(特别是在映射中)时,像这样的杂耍数组会变得非常混乱。

在 PHP 中,您可以通过以下方式轻松地将内容推送到数组的末尾:

$arr1[] = 'val1';
$arr1[] = 'val2';

如同:

$arr1 = array('val1','val2');

如果您不关心数组定位,则可以执行以下操作:

$arr2 = array(50,70); //original array
$arr2[] = 'marine';

会给:

$arr2 = array(50,70,'marine');

否则请查看PHP Array ShiftPHP Array UnshiftPHP Array Pop

于 2013-10-23T03:58:50.783 回答