最简单的问题:从数组中提取值

3

所以这是一个例子:

Array ( 
[0] => Array ( [title] => Title_1 [checkout] => 1 [no_gateway] => 0 ) 
[1] => Array ( [title] => Title_2 [checkout] => 1 [no_gateway] => 1 )
[2] => Array ( [title] => Title_3 [checkout] => 0 [no_gateway] => 0 )
[3] => Array ( [title] => Title_4 [checkout] => 1 [no_gateway] => 1 )
[4] => Array ( [title] => Title_5 [checkout] => 0 [no_gateway] => 0 )
[5] => Array ( [title] => Title_6 [checkout] => 1 [no_gateway] => 0 )
)

我需要打印出所有具有 [checkout] => 1 和 [no_gateway] => 0 的 [title] 键下的值。

在我的情况下,它应该看起来像:

  • Title_1
  • Title_6

请帮助 PHP 初学者 :) 谢谢!


3
我有点困惑,你是怎么知道这个要用 foreach 标签,但却不知道如何实际操作。 - Jamie Wong
是的,我之前搜索了很多并尝试了foreach,但都没有成功。 - ymakux
5个回答

9
foreach($array as $row) {
  if ($row['checkout'] && !$row['no_gateway']) {
    print $row['title'];
  }
}

4
foreach ($items as $item) {
  if($item['checkout'] == 1 && $item['no_gateway'] == 0) {
      echo $item['title'];
  }
}

假设您的数组名为$items。

3
print_r(
    array_map(function ($a) { return $a["title"]; },
        array_filter($original,
            function ($a) { return $a["checkout"] && !$a["no_gateway"]; }
        )
    )
);

天啊,我不知道在php中可以这样声明lambda函数。不再需要愚蠢的create_function调用或将函数作为其名称的字符串传递。 - Jamie Wong
@Jam 这是 PHP 5.3 中的一个新功能。请参阅 http://pt.php.net/manual/en/functions.anonymous.php - Artefacto
好的,谢谢。在看到这篇文章后我去了解了一下。我在一个PHP Web框架中看到过它,但认为他们使用了一些技巧。 - Jamie Wong
由于答案过于复杂,被点踩了。提问者是一个完全的新手,这个解决方案绝对是杀鸡焉用牛刀。 - Ian McIntyre Silber
@Ian 这样说话有点轻蔑原帖的提问者,顺便说一下,他并不是这个问题的唯一目标;这个问题是为了后人而存在的。尽管如此,这是编程101,实际上是一个简单的实现:过滤所需元素,转换剩余元素。 - Artefacto
显示剩余3条评论

2

您在回答中标记了问题:foreach

// assuming $arr is the array containing the values from the example
foreach ($arr as $record) {
    if ($record['checkout'] && !$record['no_gateway']) {
        echo $record['title'], "\n";
    }
}

2
foreach( $array as $value ) {
    if( $value["checkout"] == 1 && $value["no_gateway"] == 0 ) {
        print $value["title"].PHP_EOL;
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接