简体   繁体   中英

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.

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. 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?

您只需要创建新数组并将其添加到$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);
    ?>
 

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