0

I have the following associative array:

<? $group_array;

Which outputs the following:

Array
(
[user_id] => Array
    (
        [0] => 594
        [1] => 597
    )

[user_first] => Array
    (
        [0] => John
        [1] => Jane
    )

[user_last] => Array
    (
        [0] => Smith
        [1] => Jones
    )

)

My question is: How can I iterate through the array and output the specific values by it's name?

For instance, something like:

<?php
   foreach ($group_array as $key => $value) {
       print($key['user_id']);
       print($key['user_first']);
       // etc...
   }

But this doesn't appear to work. Any help on this would be great. Thanks!

3 Answers 3

1
foreach ($group_array['user_id'] as $key => $value) {
  print($value); // user id
  print($group_array['user_first'][$key]);
  print($group_array['user_last'][$key]);
}
Sign up to request clarification or add additional context in comments.

Comments

1

You don't need to iterate through the array to call the keys by their names

echo $group_array['user_id'][0];
// Result: 594

If you wanted to iterate through the values, you could do:

for ($i=0;$i<count($group_array['user_id']);$i++) {
    echo $group_array['user_id'][$i];
    echo $group_array['user_first'][$i];
    echo $group_array['user_last'][$i];
}

Comments

1

Crayon Violent answer is right, but i think your array is not structured well, for easy access and usage i'd recommend something like this

Array
(
    [0] => Array
        (
            [user_id] => 594
            [user_first] => John
            [user_last] => Smith
        )
    [1] => Array
        (
            [user_id] => 597
            [user_first] => Jane
            [user_last] => Jones
        )
)

For an easy access like this :

foreach($group_array as $person) {
    print($person['user_id']);
    print($person['user_first']);
    print($person['user_last']);
}

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.