开发者

PHP Iterate Through Associative Array and Get Specific Values

开发者 https://www.devze.com 2023-02-08 08:06 出处:网络
I have the following associative array: <? $group_array; Which outputs the following: Array ( [user_id] => Array

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 gre开发者_StackOverflow中文版at. Thanks!


foreach ($group_array['user_id'] as $key => $value) {
  print($value); // user id
  print($group_array['user_first'][$key]);
  print($group_array['user_last'][$key]);
}


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];
}


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']);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消