dtlygweb2017 2014-10-31 12:54
浏览 62
已采纳

连接两个数组的值[重复]

This question already has an answer here:

Let's assume I have an two arrays and I want to merge every value with the other value of the array.

Array 1

array (size=2)
  0 => 1
  1 => 2

Array 2

array (size=2)
  0 => 3
  1 => 4

Wanted result array / string:

array (size=4)
  0 => '1,3'
  1 => '1,4'
  2 => '2,3'
  3 => '2,4'

I can't get my head around it. Obviously I would need to merge every one array key/value with the other ones. Is there a more elegant way then doing this in a while/foreach loop?

</div>
  • 写回答

3条回答 默认 最新

  • duandang2123 2014-10-31 13:00
    关注

    You need a foreach loop inside a foreach loop. (Actualy, you will have to loop through both arrays to get a concatenated product of both arrays, you don't actually need two foreach loops). You could mix: whiles, foreach, for, or php filter/intersect array functions

    Example

    $array1 = array(1,2);
    $array2 = array(3,4);
    $result = array();
    
    foreach ($array1 as $item1){
       foreach($array2 as $item2){
          $result[] = $item1.','.$item2;
       }
    }
    

    https://eval.in/215001

    your result array Length will be array1.Length * array2.Length

    2d arrays

    You could also put an array inside an array like this:

    $array1 = array(1,2);
    $array2 = array(3,4);
    $result = array();
    
    foreach ($array1 as $item1){
       foreach($array2 as $item2){
          $result[] = array($item1, $item2);
       }
    }
    //$result[0][0] = 1 -- $result[0][1] = 3
    //$result[1][0] = 1 -- $result[1][1] = 4
    //$result[2][0] = 2 -- $result[2][1] = 3
    //$result[3][0] = 2 -- $result[3][1] = 4
    

    We call this a 2d (2 dimensional) array, because you could grapicly display this as a grid, like displayed here above. If you would put an Array, inside an Array inside an Array, you would call this a 3 dimensional array, etc.

    print_r($result); in php:

    Array
    (
        [0] => Array
            (
                [0] => 1
                [1] => 3
            )
    
        [1] => Array
            (
                [0] => 1
                [1] => 4
            )
    
        [2] => Array
            (
                [0] => 2
                [1] => 3
            )
    
        [3] => Array
            (
                [0] => 2
                [1] => 4
            )
    
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题