简体   繁体   中英

php Multidimensional array question

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. Any idea, I'm surely missing something.

Thanks guys.

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; 
}

I'm not going to ask... but try this:

<?php 

function crazy ($arr1,$arr2) {
    foreach ($arr1 as $key=>$value) {
        foreach ($arr2 as $value2) {
        $nvalue=$value;
        $nvalue[]=$value2;
        $new[]=$nvalue;
        }
    }
return $new;
}

$arr1=array(array('user'=>1,'dude'=>2),array('user'=>2,'dude'=>3));
$arr2=array(2,7,27);

print_r(crazy($arr1,$arr2));

this is tested too, http://www.ideone.com/Of126

Without testing (eek!) I imagine something like this:

function getR( $arr_one, $arr_two )
{
    $second_key = 0;
    foreach ( $arr_one as $k => &$v )
    {
        $v['menu_id'] = $second_key++;
        if ( 3 == $second_key ) $second_key = 0;
    }
    return $arr; 
}

Presumably, you're passing the first array by reference? Not sure what $arr is that you're returning though...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM