如何在foreach循环中同时打印两个数组? [英] How to print two array at the same time in a foreach loop?

查看:177
本文介绍了如何在foreach循环中同时打印两个数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
在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:

  1. 使用for循环并共享"索引变量,或者
  2. each 和朋友,或
  3. 手动进行迭代
  4. 将两个数组与 array_map
  5. 一起压缩
  1. use a for loop and "share" the index variable, or
  2. manually iterate with each and friends, or
  3. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆