首页 > 解决方案 > php - 如何过滤掉值并将它们打印到另一个数组中

问题描述

如何从数组中过滤出我的值并稍后打印它们?过滤可以通过以下方式完成:

$array = explode("<br>", $list);
foreach( $array as $key => $value){
    if (
        strpos(strtolower($value),'item to be filtered') !== FALSE ||
        strpos(strtolower($value),'another item to be filtered') !== FALSE
    ) {
        unset($array[$key]);
    }
};
$newcontent = "<pre>".implode("\n",$array)."</pre>";

但是我怎样才能在其他地方打印过滤后的数据呢?

标签: phpprintingfiltering

解决方案


正如@u_mulder 所说,您应该将结果存储在另一个数组中。

您也可以使用array_filter(), 并避免unset()调用。

$list = "item to BE filtered<br>test<br>test<br>text another item to BE filtered";

$array = explode("<br>", $list);
$other = array_filter($array, function($value) {
    return stripos($value,'item to be filtered') === FALSE &&
        stripos($value,'another item to be filtered') === FALSE;
});

$newcontent = "<pre>".implode("\n", $other)."</pre>";

推荐阅读