0

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?

2 Answers 2

3

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];
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.