如何在foreach循环中同时打印两个数组?

编程入门 行业动态 更新时间:2024-10-11 23:15:21
本文介绍了如何在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:

  • 使用for循环并共享"索引变量,或者
  • 与 each 和朋友,或
  • 手动进行迭代
  • 将两个数组与 array_map
  • 一起压缩
  • 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循环中同时打印两个数组?

    本文发布于:2023-10-28 00:04:41,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1534922.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:数组   两个   如何在   foreach

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!