如何按索引在两个数组之间合并

时间:2019-03-14 15:12:08

标签: php arrays

我有两个数组..第一个数组是这样的:

$questions = [
    "type" => "form",
    "controls" => []
];

第二个数组由如下的foreach循环填充:

$count = 0;
foreach($x as $y){
    $controls [
        "id" => $y.$count,
        "id2" => $y.$count+1,
    ]

    $count++;
}

我想将第二个数组中的所有值合并到第一个数组中的controls索引

请帮忙

2 个答案:

答案 0 :(得分:1)

无需合并,只需将结果直接放入循环中所需的位置

$questions = [
        "type" => "form",
        "controls" => []
    ];   

$count = 0;
foreach($x as $y){
    $questions['controls'][] =  ["id" => $y.$count,
                                 "id2" => $y.$count+1];
    $count++;
}

答案 1 :(得分:1)

只需:

$questions['controls'] = $controls;

您还需要修复用于填充$controls的语法,它应该是:

$controls[] = [
    "id" => $y.$count,
    "id2" => $y.$count+1,
];