Skip to content
Advertisement

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?

Advertisement

Answer

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];
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement