如何在foreach循环中同时打印两个数组? [英] How to print two array at the same time in a foreach loop?
问题描述
可能重复:
在PHP
Possible Duplicate:
Iterate through two associative arrays at the same time in PHP
我有两个数组$name[]
和$type[]
.我想像这样通过foreach循环打印那些arraya,
I have two arrays $name[]
and $type[]
. I want to print those arraya through foreach loop like this,
<?php
foreach($name as $v && $type as $t)
{
echo $v;
echo $t;
}
?>
我知道这是错误的方法,然后告诉我正确的方法.
I know this is wrong way then tell me correct way to do this.
推荐答案
您不能那样做.您需要执行以下操作之一:
You cannot do this like that. You need to do one of the following:
- use a
for
loop and "share" the index variable, or - manually iterate with
each
and friends, or - zip the two arrays together with
array_map
带有for
的示例:
Example with for
:
for ($i = 0; $i < count($name); ++$i) {
echo $name[$i];
echo $type[$i];
}
可能的问题:需要对数组进行数字索引,如果它们的长度不相同,则对使用count
的哪个数组都非常重要.您应该以较短的数组为目标,或者采取适当的措施以免索引超出范围的较长的数组.
Possible issues: The arrays need to be numerically indexed, and if they are not the same length it matters a lot which array you use count
on. You should either target the shorter array or take appropriate measures to not index into the longer array out of bounds.
reset($name); // most of the time this is not going to be needed,
reset($type); // but let's be technically accurate
while ((list($k1, $n) = each($name)) && (list($k2, $t) = each($type))) {
echo $n;
echo $t;
}
可能的问题:如果数组的长度不同,则在较短"的数组用完之后,这将停止处理元素.您可以通过将||
替换为&&
来更改它,但是随后您必须考虑$n
和$t
之一,而不总是具有有意义的值.
Possible issues: If the arrays are not the same length then this will stop processing elements after the "shorter" array runs out. You can change that by swapping ||
for &&
, but then you have to account for one of $n
and $t
not always having a meaningful value.
// array_map with null as the callback: read the docs, it's documented
$zipped = array_map(null, $name, $type);
foreach($zipped as $tuple) {
// here you could do list($n, $t) = $tuple; to get pretty variable names
echo $tuple[0]; // name
echo $tuple[1]; // type
}
可能的问题:如果两个数组的长度不相同,则较短的数组将以null扩展;否则,数组将扩展为null.您对此无能为力.此外,虽然方便,但这种方法确实会占用额外的时间和内存.
Possible issues: If the two arrays are not the same length then the shorter one will be extended with nulls; you have no control over this. Also, while convenient this approach does use additional time and memory.
这篇关于如何在foreach循环中同时打印两个数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!