rpa
rpa

Reputation: 41

combining array values in php

I would need to combine 2 or more arrays in the following way:

array1 = A, B, C
array2 = x1, x2

expected result would be:

A x1
A x2
B x1
B x2
C x1
C x2

and if I have another array, distribute the values to each item from the main array (array1)

I'm confused how to solve this. Thanks in advance

Upvotes: 1

Views: 82

Answers (2)

jjs9534
jjs9534

Reputation: 475

$arr1 = array('A','B','C');
$arr2 = array('x1','x2');

$newArr = array();

foreach($arr1 as $ar1){
    foreach($arr2 as $ar2){
        $newArr[] = $ar1 . $ar2;
    }
}

Upvotes: 2

Zinov
Zinov

Reputation: 4119

Is this that you want?

    int[] a = {1,2,3};
    int[] b = {4,5};
    //endRes = {1, 4, 1, 5, 2, 4, 2, 5, 3, 4, 3, 5}
    int[] endRes = new int[ (a.length * b.length)*2 ]; 

    int k = 0;

    for(int i = 0; i < a.length; i ++){
        for(int j = 0; j < b.length; j++){
            endRes[k] = a[i];
            endRes[k + 1] = b[j];
            k += 2;
        }
    }

Upvotes: 0

Related Questions