多维关联数组 (PHP)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18648413/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Multidimensional Associative Array (PHP)
提问by MillerMedia
I'm new to arrays in PHP and am trying to wrap my mind around how to make a multidimensional associative array. I'd like the array to look like this when I use print_r:
我是 PHP 中的数组的新手,我正在努力思考如何制作多维关联数组。当我使用 print_r 时,我希望数组看起来像这样:
Array ( [0] => Array ( [alert] => alert [email] => Test ) )
Instead I get this:
相反,我得到了这个:
Array ( [0] => Array ( [alert] => Array ( [email] => Test ) ) )
The code I'm using is this:
我正在使用的代码是这样的:
$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 somewhat on the right track though?:
我认为尝试这样的事情会奏效,但显然我的语法有点不对。不过,我认为我有点走对了?:
$alert_array[][["alert"]["email"]] = "Test";
Thank for your help (sorry if this is super basic, I couldn't find any questions that addressed this exactly)!
感谢您的帮助(对不起,如果这是超级基本的,我找不到任何完全解决这个问题的问题)!
回答by Dejan Marjanovic
$alert_array = array();
$alert_array[] = array('alert' => 'alert', 'email' => 'Test');
...
var_dump($alert_array);
In your case you'd have to specify key
like so:
在您的情况下,您必须key
像这样指定:
$alert_array[$key]["alert"] = "alert";
$alert_array[$key]["email"] = "Test";
You'd have to have a loop with counter too.
你也必须有一个带计数器的循环。
If you're using PHP 5.4+ you could use short array syntax:
如果您使用的是 PHP 5.4+,则可以使用短数组语法:
$alert_array = [];
$alert_array[] = ['alert' => 'alert', 'email' => 'Test'];
回答by Sukumar
if you put an already existing Array inside a new Array using array function, then your result will be multi-dimensional 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, result will be one-dimensional array
在这种情况下,结果将是一维数组
$alert_array = array();
while($variable = mysqli_fetch_assoc($something)) {
$alert_array[] = $variable;
}
please also refer array function
另请参考数组函数