[英]PHP - array_push to create a multidimensional array
I am trying to create an array which will have two key/value pairs for each user.我正在尝试创建一个数组,该数组将为每个用户提供两个键/值对。 I would like to add their user ID as well as their name.
我想添加他们的用户 ID 以及他们的姓名。
Currently I have this:目前我有这个:
<?php
$userArray = array();
foreach ($users as $user) {
array_push($userArray, $user->ID, $user->name);
}
print_r($userArray);
?>
This gives me the following:这给了我以下内容:
Array ([0] => 167 [1] => Bill [2] => 686 [3] => Jim [4] => 279 [5] => Tom)
However, to make it easier to read and work with, I would prefer that it shows user_id
and user_name
as the keys, rather than just the index.但是,为了更易于阅读和使用,我更愿意将
user_id
和user_name
显示为键,而不仅仅是索引。 I believe this is what's called a multidimensional array and would look more like this:我相信这就是所谓的多维数组,看起来更像这样:
Array (
0 => array(
'user_id' => 167,
'user_name' => 'Bill'
),
1 => array(
'user_id' => 686,
'user_name' => 'Jim'
),
2 => array(
'user_id' => 279,
'user_name' => 'Tom'
)
)
My question is how would I build an array like this within my foreach
loop?我的问题是如何在
foreach
循环中构建这样的数组?
您只需要创建新数组并将其添加到$userArray
,但我使用[]
而不是array_push()
......
$userArray[] = [ 'user_id' => $user->ID, 'user_name' => $user->name];
you should be pushing a new array, like this :您应该推送一个新数组,如下所示:
<?php
$userArray = array();
foreach ($users as $user) {
array_push($userArray, ['user_id' => $user->ID, 'user_id' => $user->name]);
}
print_r($userArray);
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.