dongtiao6362
dongtiao6362
2017-08-14 04:31

如何在php中连接两个数组? [重复]

已采纳

This question already has an answer here:

I want to concatenate two arrays like this:

$cars=array("Volvo","BMW","Toyota");
$speed=array("210","220","330");
$merge=array_merge($cars,$speed);

Expected output:

array(
    0=>Volvo 210
    1=>BMW 220 
    2=>Toyota 330
)
</div>
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

5条回答

  • douxian9060 douxian9060 4年前

    You can also try this simplest one. Here we are using array_map to achieve desired output

    Try this code snippet here

    <?php
    
    $cars = array('Volvo', 'BMW', 'Toyota');
    $speed = array('210', '220', '330');
    
    $result = array_map(function($car, $speed) {
        return $car . ' ' . $speed;
    }, $cars, $speed);
    
    var_dump($result);
    
    点赞 评论 复制链接分享
  • doufang3001 doufang3001 4年前

    This will put all values into one array.

       <?php 
           $cars=array("Volvo","BMW","Toyota");
           $speed=array("210","220","330");
           $merge=[];
           for ($x = 0; $x < sizeof($cars); $x++) {
              array_push($merge,$cars[$x] .' '. $speed[$x]);
           } 
        ?>
    

    EDIT As I have recieved a downvote for some unknown reason I will explain my answer.

    Loop through one array in this case the cars array, then add a concatination of the two arrays to the merge array.

    This code will achieve the same result as the accepted answer.

    点赞 评论 复制链接分享
  • douyou2234 douyou2234 4年前

    Combine both array and push into another array. See example:

    $speed=array("210","220","330");
    $merge=array_combine($cars,$speed);
    

    $arr= array(); // new array for storing desired data

    foreach($merge as $k=>$v){
    $arr[] = $k .' '.$v;
    }
    print_r($arr);
    
    Output: 
    Array
    (
        [0] => Volvo 210
        [1] => BMW 220
        [2] => Toyota 330
    )
    
    点赞 评论 复制链接分享
  • dpn517111 dpn517111 4年前

    There is no method in php for such a scenario, but you can do this:

    $cars=array("Volvo","BMW","Toyota");    
    $speed=array("210","220","330");
    
    $newArr = array();
    
    foreach($cars as $cKey => $cVal){    
      $newArr[] = $cVal.' '.$speed[$cKey];    
    }
    
    print_r($newArr);
    
    点赞 评论 复制链接分享
  • dphfwzn8269 dphfwzn8269 4年前

    1st : Loop the first array using foreach

    2nd : concatenate the both variable

    3rd : Push the value into new array .

    <?php
    
    $cars=array("Volvo","BMW","Toyota");
    $speed=array("210","220","330");
    $new_array =array();
    
    foreach($cars as $key=>$c)
    {
        $new_array[]=$c.' '.$speed[$key];   
    }
    
    print_r($new_array);
    
    ?>
    

    Note : Above code will work only when both array have same count of elements and same index .

    点赞 评论 复制链接分享