简体   繁体   中英

How to add indexed arrays to an array on a certain index using PHP?

I'm trying to add indexed arrays to a final array on a certain index. So far, I have tried this:

$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);

But it's not working. The final array on the $id index has NULL value. What am I missing? Can someone help me?

array_push is used for appending something to the end of array, it should not be used with specific key. You want something more like this:

<?php
$lista = array();
$id = '1234';

$lista2 = array(
    'chave1' => 'valor1',
    'chave2' => 'valor2',
    'chave3' => 'valor3'
);

$lista3 = array(
    'chave4' => 'valor4',
    'chave5' => 'valor5',
    'chave6' => 'valor6'
);

$lista[$id] = $lista2 + $lista3;

print_r($lista);

output:

Array
(
    [1234] => Array
        (
            [chave1] => valor1
            [chave2] => valor2
            [chave3] => valor3
            [chave4] => valor4
            [chave5] => valor5
            [chave6] => valor6
        )

)

EDIT:

If you need it in loop (which does not look correct, so you should reconsider structure of your code...):

<?php
$lista = array();
$id = '1234';

$lista1 = array(
    'chave7' => 'valor7',
    'chave8' => 'valor8',
    'chave9' => 'valor9'
);

$lista2 = array(
    'chave1' => 'valor1',
    'chave2' => 'valor2',
    'chave3' => 'valor3'
);

$lista3 = array(
    'chave4' => 'valor4',
    'chave5' => 'valor5',
    'chave6' => 'valor6'
);
$lista[$id] = [];
for ($i = 1; $i <= 3; $i++) {
    $lista[$id] += ${'lista' . $i};
}
print_r($lista);

Try assigning the value directly: $lista[$id] = $lista2;

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