我有以下关联数组:
<? $group_array;
其中输出以下内容:
Array
(
[user_id] => Array
(
[0] => 594
[1] => 597
)
[user_first] => Array
(
[0] => John
[1] => Jane
)
[user_last] => Array
(
[0] => Smith
[1] => Jones
)
)
我的问题是:如何迭代数组并按名称输出特定值?
例如:
<?php
foreach ($group_array as $key => $value) {
print($key['user_id']);
print($key['user_first']);
// etc...
}
但这似乎不起作用。对此的任何帮助都会很棒。谢谢!
答案 0 :(得分: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]);
}
答案 1 :(得分:1)
您无需遍历数组以按名称
调用键echo $group_array['user_id'][0];
// Result: 594
如果你想迭代这些值,你可以这样做:
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];
}
答案 2 :(得分:1)
蜡笔暴力回答是对的,但我认为你的阵列结构不合理,为了方便访问和使用我会推荐这样的东西
Array
(
[0] => Array
(
[user_id] => 594
[user_first] => John
[user_last] => Smith
)
[1] => Array
(
[user_id] => 597
[user_first] => Jane
[user_last] => Jones
)
)
为了方便访问:
foreach($group_array as $person) {
print($person['user_id']);
print($person['user_first']);
print($person['user_last']);
}