如何使用 PHP 将索引数组添加到某个索引上的数组?

我正在尝试将索引数组添加到某个索引上的最终数组。到目前为止,我已经试过了:


$lista = array();

$id = '1234';


$lista2 = array(

    'chave1' => 'valor1',

    'chave2' => 'valor2',

    'chave3' => 'valor3'

);


$lista3 = array(

    'chave4' => 'valor4',

    'chave5' => 'valor5',

    'chave6' => 'valor6'

);


array_push($lista[$id], $lista2);

array_push($lista[$id], $lista3);

但它不起作用。$id 索引上的最终数组具有 NULL 值。我错过了什么?有人能帮我吗?


三国纷争
浏览 114回答 2
2回答

潇潇雨雨

array_push用于将某些内容附加到数组末尾,不应与特定键一起使用。你想要更像这样的东西:<?php$lista = array();$id = '1234';$lista2 = array(&nbsp; &nbsp; 'chave1' => 'valor1',&nbsp; &nbsp; 'chave2' => 'valor2',&nbsp; &nbsp; 'chave3' => 'valor3');$lista3 = array(&nbsp; &nbsp; 'chave4' => 'valor4',&nbsp; &nbsp; 'chave5' => 'valor5',&nbsp; &nbsp; 'chave6' => 'valor6');$lista[$id] = $lista2 + $lista3;print_r($lista);输出:Array(&nbsp; &nbsp; [1234] => Array&nbsp; &nbsp; &nbsp; &nbsp; (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [chave1] => valor1&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [chave2] => valor2&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [chave3] => valor3&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [chave4] => valor4&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [chave5] => valor5&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [chave6] => valor6&nbsp; &nbsp; &nbsp; &nbsp; ))编辑:如果你在循环中需要它(这看起来不正确,所以你应该重新考虑你的代码结构......):<?php$lista = array();$id = '1234';$lista1 = array(&nbsp; &nbsp; 'chave7' => 'valor7',&nbsp; &nbsp; 'chave8' => 'valor8',&nbsp; &nbsp; 'chave9' => 'valor9');$lista2 = array(&nbsp; &nbsp; 'chave1' => 'valor1',&nbsp; &nbsp; 'chave2' => 'valor2',&nbsp; &nbsp; 'chave3' => 'valor3');$lista3 = array(&nbsp; &nbsp; 'chave4' => 'valor4',&nbsp; &nbsp; 'chave5' => 'valor5',&nbsp; &nbsp; 'chave6' => 'valor6');$lista[$id] = [];for ($i = 1; $i <= 3; $i++) {&nbsp; &nbsp; $lista[$id] += ${'lista' . $i};}print_r($lista);

汪汪一只猫

尝试直接赋值:$lista[$id] = $lista2;
打开App,查看更多内容
随时随地看视频慕课网APP