Multidimensional Associative Array (PHP)

I am new to PHP arrays and trying to think about how to create a multidimensional associative array. I would like the array to look like this when I use print_r:

Array ( [0] => Array ( [alert] => alert [email] => Test ) ) 

Instead, I get the following:

 Array ( [0] => Array ( [alert] => Array ( [email] => Test ) ) ) 

The code I use is as follows:

 $alert_array = array(); $alert_array[]["alert"]["email"] = "Test"; 

I thought trying something like this would work, but obviously my syntax is a bit off. I think I'm a little right, but ?:

 $alert_array[][["alert"]["email"]] = "Test"; 

Thank you for your help (sorry if this is super basic, I could not find any questions that related to this)!

+6
source share
2 answers
 $alert_array = array(); $alert_array[] = array('alert' => 'alert', 'email' => 'Test'); ... var_dump($alert_array); 

In your case, you need to specify key like this:

 $alert_array[$key]["alert"] = "alert"; $alert_array[$key]["email"] = "Test"; 

You should also have a loop with a counter.

If you are using PHP 5.4+, you can use the syntax of short arrays:

 $alert_array = []; $alert_array[] = ['alert' => 'alert', 'email' => 'Test']; 
+19
source

if you put an existing array into a new array using an array function , then your result will be a multidimensional array

  $alert_array = array(); $alert_array[] = array('alert' => 'alert', 'email' => 'Test'); print_r($alert_array); /* result will be Array ( [0] => Array ( [alert] => alert [email] => Test ) ) */ 

In this case, the result will be a one-dimensional array

 $alert_array = array(); while($variable = mysqli_fetch_assoc($something)) { $alert_array[] = $variable; } 

request also reference array function

0
source

Source: https://habr.com/ru/post/953285/


All Articles