user13286
user13286

Reputation: 3075

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?

Upvotes: 0

Views: 99

Answers (2)

Hamza El Founassi
Hamza El Founassi

Reputation: 36

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);
    ?>
 

Upvotes: 2

Nigel Ren
Nigel Ren

Reputation: 57121

You just need to create the new array and add it to the $userArray, I use [] instead of array_push() though...

$userArray[] = [ 'user_id' => $user->ID, 'user_name' => $user->name];

Upvotes: 3

Related Questions