简体   繁体   中英

Append/merge values to a Two Dimensional Array from a One Dimensional Array

Im kind of stuck since I can't figure out how to solve this problem. I can't seem to find the exact solution on the internet so that's why I am asking it here.

Example:

# array1
Array
(
    [0] => Array
        (
            [0] => Product1 
            [1] => Description product 1          
        )

    [1] => Array
        (
            [0] => Product2
            [1] => Description product 2       
        )

    [2] => Array
        (
            [0] => Product3
            [1] => Description product 3       
        )
)

# array2
Array
(       
    [0] => 10
    [1] => 20 
    [2] => 30
)

#resultant array
Array
(
    [0] => Array
        (
            [0] => Product1 
            [1] => Description product 1
            [2] => 10
        )

    [1] => Array
        (
            [0] => Product2
            [1] => Description product 2
            [2] => 20       
        )

    [2] => Array
        (
            [0] => Product3
            [1] => Description product 3  
            [2] => 30    
        )
)

I am programming in PHP, using no frameworks. I would like some help to find something that can result in #resultant array .

I have tried using the build in PHP functions array_merge(); . But that doesn't work. I am guessing I need some kind of foreach or loop but I can't figure out how to build/write that.

Thanks for reading, I hope to find a solution or a lead on where to start.

Just loop array2 and add the value to array1.

foreach($arr2 as $key => $val){
    $arr1[$key][] = $val;
}

Please try to do like this

$a = array(
    '0' => array(
        '0' => 1,
        '1' => 2
    ),
    '1' => array(
        '0' => 3,
        '1' => 4
    ), 
);
$b = array(
    '0' => 10,
    '1' => 20
);
$c = $a;
foreach ($c as $key => $value) {
    array_push($c[$key], $b[$key]);
}
print_r($c);

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