【问题标题】:foreach loop through multidimensional array and only echo arrays containing specific valueforeach 循环遍历多维数组,并且只回显包含特定值的数组
【发布时间】:2015-01-11 20:07:53
【问题描述】:

我有一个存储在$t_comments 中的多维数组,看起来像这样:

Array (
    [0] => Array
        (
            [0] => 889
            [1] => First comment
            [2] => 8128912812
            [3] => approved
        )

    [1] => Array
        (
            [0] => 201
            [1] => This is the second comment
            [2] => 333333
            [3] => deleted
        )

    // There is more...
)

目前,我像这样循环遍历数组:

foreach($t_comments as $t_comment) {
    echo $t_comment[0]; // id
    echo $t_comment[1]; // comment
    echo $t_comment[2]; // timestamp
    echo $t_comment[3]; // status
}

我想对数组进行 foreach 循环,并且只显示具有值 approved 的数组(如上所示)。 在考虑性能时我该怎么做

【问题讨论】:

  • 你有没有尝试过自己解决问题?
  • 我能想到的最接近的方法是如果状态为“已批准”,则执行 if 语句检查每个循环,但在考虑性能时,这似乎是一种不好的方法。
  • 实际上我认为关于性能的最佳方法是@HenrikPetterson 建议的。检查这些benchmarks

标签: php arrays multidimensional-array foreach


【解决方案1】:

最好的解决方案是一开始就不必检查。

如果您控制了膨胀 $t_comment 数组的源,您可以使其不发送未批准的 cmets。

例如,如果你有类似的东西:

$t_comments = get_comments

你可以使用类似的东西:

$t_comments = get_approved_comments

但如果你不能,那么你将不得不遍历每个数组来寻找你想要的东西。

为此,您必须在 foreach 中放置一个“if”以检查您的变量内容,以便您知道它已被批准,然后您知道您可以显示它,并对其进行响应。

例子:

foreach($t_comments as $t_comment) {
    if($t_comment[3]=="approved"){
          echo $t_comment[0];
          echo $t_comment[1];
          echo $t_comment[2];
          echo $t_comment[3]; 
    }
}

【讨论】:

  • 您能详细说明一下吗?你正在使用我尚未学习的术语:)
  • 这是我在对我的问题的评论中写的,但在考虑性能时,这似乎不是最好的方法......
  • 通常我会有一个带有状态的字段,这样我就可以检查它而不是评论说已批准。
  • 在考虑性能时,这是唯一且最好的方法吗?
  • 好吧,如果你控制了你的来源,你可以让它不发送未经批准的 cmets,这样你就不需要检查它。
猜你喜欢
  • 1970-01-01
  • 2010-10-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-26
  • 2013-04-01
相关资源
最近更新 更多