Search code examples
phparraysarray-mergearray-push

Adding datas into an array / coupling arrays


I haves two arrays :

The first one :

$positions = array(0 => array(6.35,3.93), 1 => array(16.85,3.93),  2 => array(6.35,10.9),  3 => array(16.85,10.9), 4 => array(6.35,18.48),  5 => array(16.85,18.48),  6 =>a rray(6.35,25.45), 7 => array(16.85,25.45));

The second one :

   $coupons = Array ( [0] => NGP7xdaERK [1] => LntKT38dXj [2] => UBG2fplvnx [3] => ymMkO6EF16 [4] => zsZCasRWrj [5] => cl6UJ1a7VS [6] => lrjc5vnpl6 [7] => mExuzQBOLs ) ;

I'd like to merge those two arrays to have something like this :

array(0 => array(6.35,3.93, NGP7xdaERK ), 1 => array(16.85,3.93, LntKT38dXj ), ...

I'm not really familiar with handling arrays like that, I've heard of array_push and array_merge, I know that I have to use a foreach loop in order to avoid keys to be added, but I don't know how to make something concrete with such informtion ^^

Could you guys help me ? :)

Thanks a lot :)


Solution

  • Assuming your arrays are both always the same length. You could use this:

    $positions = array(0 => array(6.35,3.93), 1 => array(16.85,3.93),  2 => array(6.35,10.9),  3 => array(16.85,10.9), 4 => array(6.35,18.48),  5 => array(16.85,18.48),  6 => array(6.35,25.45), 7 => array(16.85,25.45));
    
    $coupons = array ( 0 => 'NGP7xdaERK', 1 => 'LntKT38dXj', 2 => 'UBG2fplvnx', 3 => 'ymMkO6EF16', 4 => 'zsZCasRWrj', 5 => 'cl6UJ1a7VS', 6 => 'lrjc5vnpl6', 7 => 'mExuzQBOLs' ) ;
    
    $result = array();
    
    foreach($positions as $i=>$pos ) {
        $result[$i] = array_merge($pos, (array)$coupons[$i]);
    }
    
    print_r($result);
    

    Result:

    Array
    (
        [0] => Array
            (
                [0] => 6.35
                [1] => 3.93
                [2] => NGP7xdaERK
            )
    
        [1] => Array
            (
                [0] => 16.85
                [1] => 3.93
                [2] => LntKT38dXj
            )
    
        [2] => Array
            (
                [0] => 6.35
                [1] => 10.9
                [2] => UBG2fplvnx
            )
    
        [3] => Array
            (
                [0] => 16.85
                [1] => 10.9
                [2] => ymMkO6EF16
            )
    
        [4] => Array
            (
                [0] => 6.35
                [1] => 18.48
                [2] => zsZCasRWrj
            )
    
        [5] => Array
            (
                [0] => 16.85
                [1] => 18.48
                [2] => cl6UJ1a7VS
            )
    
        [6] => Array
            (
                [0] => 6.35
                [1] => 25.45
                [2] => lrjc5vnpl6
            )
    
        [7] => Array
            (
                [0] => 16.85
                [1] => 25.45
                [2] => mExuzQBOLs
            )
    
    )