简体   繁体   English

将值从一维数组追加/合并到二维数组

[英]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. 我使用PHP编程,没有使用任何框架。 I would like some help to find something that can result in #resultant array . 我希望获得一些帮助,以找到可以导致#resultant array

I have tried using the build in PHP functions array_merge(); 我试过在PHP函数array_merge();使用构建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. 我猜我需要某种foreach或循环,但我不知道如何构建/编写它。

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. 只需循环array2并将其值添加到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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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