phparraysmultidimensional-arraycartesian-product

Duplicate and append each row of a 2d array using a flat aray


So I have an array like the following:

Array
(
    [0] => Array
        (
            [user_id] => 684
            [sec_id] => 2
            [rank_id] => 1
            [rank] => usr
            
        )

    [1] => Array
        (
            [user_id] => 693
            [sec_id] => 3
            [rank_id] => 5
            [rank] => usr
            
        )
)

And I have another array like this

Array
(
    [0] => 2
    [1] => 7
    [2] => 27
)

I want the value of the second array to be added at the end of each arrays of the 1st array, and it should be multiplied. I mean, if I have 100 arrays in the first array, and 3 elements in the second array, I should have 300 in the resulting array.

Taking example of the above, I would like to have something as follows:

user_id | sec_id | rank_id | rank | menu_id
684 |        2 |       1 |    usr |    2
684 |        2 |       1 |    usr |    7
684 |        2 |       1 |    usr |   27
693 |        3 |       5 |    usr |    2
693 |        3 |       5 |    usr |    7
693 |        3 |       5 |    usr |   27

I tried with the following function, but it's not working.

function getR($arr_one,$arr_two) {
    foreach ($arr_one as $k=>&$v) {
        foreach ($arr_two as $x=>&$y) { $v['menu_id'] = $y;  }
    }
    return $arr_one; 
}

This is just making an array like this:

user_id | sec_id | rank_id | rank | menu_id
684 |        2 |       1 |    usr |   27
693 |        3 |       5 |    usr |   27

Means, it's just adding menu_id at the end of each element of the first array, but not multiplying.


Solution

  • function getR($arr_one,$arr_two) {
        $new_arr = array();
        foreach ($arr_one as $k=>$v) {
            foreach ($arr_two as $x=>$y) {
                $this_item = $v;
                $this_item['menu_id'] = $y;
                $new_arr[] = $this_item;
            }
        }
        return $new_arr; 
    }