【问题标题】:For Each loop with 2 parent 'columns'对于每个具有 2 个父“列”的循环
【发布时间】:2021-01-09 20:12:23
【问题描述】:

我正在尝试扩展一些工作代码,但不知道该怎么做。 基本上,信息可以在信息或其他标题下。 但我不关心这种分裂,我只想为他们所有人一起做一个 foreach。

基本上我目前为每个循环运行一个这样的:

foreach ($info_array['information'] as $item) {... do something }

是否有可能以某种方式说,对于每个 info_array 'information' & 'othertitle' as $item?

数组的结构如下:

information
   random number
      price
      amount
      total
   random number
      price
      amount
      total
othertitle
   random number
      price
      amount
      total
   random number
      price
      amount
      total

我试过了,但是没用:

foreach ($item_array['information'] as $item and $item_array['othertitle'] as $item)

【问题讨论】:

  • 显示你想对循环中的项目做什么。
  • 你试图通过这些双循环来实现什么?
  • 我不想做双循环。我只想要“随机数”下的所有数据,我不在乎父母是“信息”还是“其他标题”。我只是不知道如何循环以一次获取“信息”和“其他标题”部分的所有价格/金额/总计
  • 作为othertitle 跟随 information 两个循环 - 一个接一个 - 就足够了。
  • @u_mulder 所以最好的办法不是把它结合起来吗?但只是一个接一个地跑? (所以每个循环 2 个?)(我确实想到了这一点,但认为/希望有一个更优雅的解决方案 XD)

标签: php arrays loops foreach


【解决方案1】:

想到的第一个想法就是使用两个循环——第一个循环遍历$item_array['information'],第二个循环遍历$item_array['othertitle']。像这样的:

foreach ($item_array['information'] as $item) {
    echo $item['key1'] . ' -> ' . $item['key2'];
}
foreach ($item_array['othertitle'] as $item) {
    echo $item['key1'] . ' -> ' . $item['key2'];
}

但是,如果你对每个数组的每个元素做同样的输出,你可以这样做:

$keys = ['information', 'othertitle'];
foreach ($keys as $key) {
    echo 'Key is ' . $key . '<br />';
    foreach ($item_array[$key] as $item) {
        echo $item['key1'] . ' -> ' . $item['key2'];
    }
}

即使是数组的输出也不同 - 你可以用这种方式解决它:

$keys = ['information', 'othertitle'];
foreach ($keys as $key) {
    echo 'Key is ' . $key . '<br />';
    foreach ($item_array[$key] as $item) {
        if ('information' === $key) {
            echo 'Info: ' . $item['key1'] . ' -> ' . $item['key2'];
        } else {
            echo 'Ttile: ' . $item['key1'] . ' and ' . $item['key2'];
        }
    }
}

如果您必须遍历$item_array 的所有子数组,则解决方案与@AbraCadaver 中的答案相同:

foreach ($item_array as $key => $items) {
    echo 'Key is ' . $key . '<br />';
    foreach ($items as $item) {
        if ('information' === $key) {
            echo 'Info: ' . $item['key1'] . ' -> ' . $item['key2'];
        } else {
            echo 'Ttile: ' . $item['key1'] . ' and ' . $item['key2'];
        }
    }
}

【讨论】:

  • 谢谢你,我现在解决了,我从你的两个答案中都使用了一些,但最终主要部分只用了 2 个循环,所以谢谢!
【解决方案2】:

既然您知道索引,您可以array_merge 或使用+

foreach ($item_array['information'] + $item_array['othertitle'] as $item) {
    // do something
}

否则你需要两个循环:

foreach ($item_array as $array) {
    foreach($array as $item) {
        // do something
    }
}

【讨论】:

    猜你喜欢
    • 2022-12-13
    • 2016-11-25
    • 1970-01-01
    • 1970-01-01
    • 2014-06-17
    • 2013-11-22
    • 2020-05-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多