PHP如何用array_filter过滤数组?

Array

(

    [0] => Array

        (

            [id] => 1

            [name] => 你好,234

            [cate] =>  生活日记

       )


    [1] => Array

        (

            [id] => 2

            [name] => 79798

            [cate] => 摄影美图


        )


    [2] => Array

        (

            [id] => 3

            [name] => 567567

            [cate] =>  生活日记

       )


)

过滤里面cate = 摄影美图,其它全部保留,效果是

Array

(

   [0] => Array

       (

           [id] => 1

           [name] => 你好,234

           [cate] =>  生活日记

       )


   [1] => Array

       (

           [id] => 2

           [name] => 79798

           [cate] => 生活日记


      )

如何用array_filter实现呢? 感觉array_filter不太好用。

汪汪一只猫
浏览 9047回答 3
3回答

缥缈止盈

啥也不说,直接上代码,可惜php的闭包跟js一样又臭又长:$data = [   [ 'id' => 1, 'name' => '你好,234', 'cate' => '生活日记'],   [ 'id' => 2, 'name' => '79798', 'cate' => '摄影美图'],   [ 'id' => 3, 'name' => '567567', 'cate' => '生活日记'],];$filtered = array_filter($data, function($item){                  return $item['cate'] !== '摄影美图';             });print_r($filtered);

料青山看我应如是

注意看array_filter的第二个参数,第二个参数是一个自定义函数。这个自定义函数是为了设置过滤条件。<?php&nbsp; &nbsp; $arr = array(&nbsp; &nbsp; &nbsp; &nbsp; array('id'=>1, 'cate'=>"生活日记"),&nbsp; &nbsp; &nbsp; &nbsp; array('id'=>2, 'cate'=>"摄影美图"),&nbsp; &nbsp; );&nbsp; &nbsp; var_dump($arr);&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; function filter($rows){&nbsp; &nbsp; &nbsp; &nbsp; if($rows['cate']==="摄影美图"){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; &nbsp; &nbsp; }else{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return true;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; $arr = array_filter($arr, 'filter');&nbsp; &nbsp; var_dump($arr);

阿波罗的战车

我觉得不用array_filter也能达到目的呀<?php&nbsp; &nbsp;&nbsp; &nbsp;$oriArr = array(&nbsp; &nbsp; &nbsp; &nbsp;0 => array('id' => '1', 'name' => '你好,234', 'cate' => '生活日记'),&nbsp; &nbsp; &nbsp; &nbsp;1 => array('id' => '2', 'name' => '79798', 'cate' => '摄影美图'),&nbsp; &nbsp; &nbsp; &nbsp;2 => array('id' => '3', 'name' => '567567', 'cate' => '生活日记'),&nbsp; &nbsp;);&nbsp; &nbsp;$resultArr = array();&nbsp; &nbsp;foreach ($oriArr as $key => $value)&nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; &nbsp;if ($value['cate'] === '摄影美图')&nbsp; &nbsp; &nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;continue;&nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp; &nbsp;else&nbsp; &nbsp; &nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;$resultArr[] = $value;&nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp;}&nbsp; &nbsp;print_r($resultArr);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java