简体   繁体   中英

Add Associative Arrays in PHP to associative array using the same key

I have issued with overriding assoc array in php by adding under the same key second associative array with different key.

my function is:

$this->data[$period]= [$i=> ['key'=>$value, 'key1'=>$value1]];

period takes fx 1,2 and $i takes fx 3,4,5.

the thing is that i want to add to $period key few tables with different $i key, but its overriding the whole array. For example if we take that $period = 1, and $i = 3 and 4:

$data[1] = [3=> ['key'=>key, 'key1'=>key1 ]];
$data[1] = [4=> ['key'=>keyX, 'key1'=>key1X ]];

if i var_dump table it shows only the data table contains

$data[1] = [4=> ['key'=>keyX, 'key1'=>key1X ]] 

and table with $i key = =3 is deleted.

how to add it correctly to have under $period 1 this two tables?

I know i can add extra assoc array before this two but maybe it is sth more proper?

Thanks!

You can't have elements in an array with the same key, so you need to make $data[$period] an array itself and push the tables into it:

$data[1][] = [3=> ['key'=>'key', 'key1'=>'key1' ]];
$data[1][] = [4=> ['key'=>'keyX', 'key1'=>'key1X' ]];
print_r($data[1]);

Output:

Array
(
    [0] => Array
        (
            [3] => Array
                (
                    [key] => key
                    [key1] => key1
                )
        )
    [1] => Array
        (
            [4] => Array
                (
                    [key] => keyX
                    [key1] => key1X
                )
        )
)

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