2017-08-14 04:31

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


This question already has an answer here:

I want to concatenate two arrays like this:


Expected output:

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


  • 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

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

    This will put all values into one array.

           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:


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

    foreach($merge as $k=>$v){
    $arr[] = $k .' '.$v;
        [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:

    $newArr = array();
    foreach($cars as $cKey => $cVal){    
      $newArr[] = $cVal.' '.$speed[$cKey];    
    点赞 评论 复制链接分享
  • dphfwzn8269 dphfwzn8269 4年前

    1st : Loop the first array using foreach

    2nd : concatenate the both variable

    3rd : Push the value into new array .

    $new_array =array();
    foreach($cars as $key=>$c)
        $new_array[]=$c.' '.$speed[$key];   

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

    点赞 评论 复制链接分享