简体   繁体   中英

How can I append an array as an element to another array in PHP?

So I have lots of arrays of the form:

$e = array( 
  "key1" => "value1",
  "key2" => "value2",
  "key3" => "value3",
  "key4" =? "value4"
);

And another array just declared as:

$a = array( );

What I want is to append $e to $a as an element, so

$a[0] = array( 
  "key1" => "value1",
  "key2" => "value2",
  "key3" => "value3",
  "key4" =? "value4"
);

So I can then go:

$count = count( $a );
for ( $j = 0; $j < $count; $j++ )
{
  echo $a[$j]["key1"];
}

and it will print "value1".

I will be repeating this process for all of the $e, so $a may not always be empty when the $e is appended - it may have had other $e appended previously. I thought that array_push would do this but it doesn't. Thanks for any help.

The quick and dirty way is pretty simple:

$a[] = $e;

and then do it again for any additional arrays. That will fill in the $a array starting with index zero and incrementing up.

If you wanted to use some sort of keys, you could do:

$a['firstarray'] = $e;

and accomplish much the same thing. The difference is that since keys must be unique, a screwup in that second method could overwrite an existing element. The first method has no chance of that happening.

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