微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

For Each 具有 2 个父“列”的循环

如何解决For Each 具有 2 个父“列”的循环

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

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

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

是否有可能以某种方式说,对于每个 info_array 'information' 和 'othertitle' 作为 $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)

解决方法

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

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

否则你需要两个循环:

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

想到的第一个想法就是使用两个循环——第一个循环遍历 $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'];
        }
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。