PHP array_filter用争论回调 [英] PHP array_filter with argument to callback

查看:112
本文介绍了PHP array_filter用争论回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要过滤在PHP中的数组,但我不知道如何将参数传递给回调。基本上我有2个比较,让对数组中的每个项目。

I need to filter an array in PHP but am not sure how to pass an argument to the callback. Essentially I have 2 comparisons to make on each item in the array.

// This data will be sent to the function as JSON so I'm "creating" the JSON here.
$data = json_encode(Array(
    Array("StartDate"=>"2014/07/31","LocZipCode"=>"19406","LocationURL"=>"FSU","EventType"=>"UN"),
    Array("StartDate"=>"2014/08/31","LocZipCode"=>"23513","LocationURL"=>"FSU","EventType"=>"UN"),
    Array("StartDate"=>"2014/07/31","LocZipCode"=>"92108","LocationURL"=>"BU","EventType"=>"UN"),
    Array("StartDate"=>"2014/09/30","LocZipCode"=>"78661","LocationURL"=>"BU","EventType"=>"UN")
));

// even using a global variable doesn't 
// make it visible in getUniv() function
global $univ_seg;
$univ_seg = 'FSU';

getUA($data, $univ_seg);

function getUniv($var){
    return($var["EventType"] == "UN" && $var["LocationURL"] == $univ_seg);
}

function getUA($data, $univ_seg) {
    $univ_sched = json_decode($data, true);
    $re = array_filter($univ_sched, "getUniv");
    print_r($re); 
}

我也用一个lambda尝试,但我不能使它工作。任何想法??

I've also tried using a lambda but I just can't make it work. Any ideas??

推荐答案

我得到了它使用一个对象的工作,的http://www.php.net/manual/en/language.pseudo-types.php#language.types.callback

I got it to work using an object, http://www.php.net/manual/en/language.pseudo-types.php#language.types.callback

class univFilter {
    public $univ_seg;
    public function filter($var) {
        if($var["EventType"] == "UN" && $var["LocationURL"] == $this->univ_seg)
            return true;
          else
            return false;
    }
}

$data = json_encode(Array(
    Array("StartDate"=>"2014/07/31","LocZipCode"=>"19406","LocationURL"=>"FSU","EventType"=>"UN"),
    Array("StartDate"=>"2014/08/31","LocZipCode"=>"23513","LocationURL"=>"FSU","EventType"=>"UN"),
    Array("StartDate"=>"2014/11/30","LocZipCode"=>"92108","LocationURL"=>"BU","EventType"=>"UN"),
    Array("StartDate"=>"2014/09/30","LocZipCode"=>"78661","LocationURL"=>"BU","EventType"=>"UN")
));

$univ_seg = "BU";
getUA($data,$univ_seg);

function getUA($data, $univ_seg) {
    $f = new univFilter();
    $f->univ_seg = $univ_seg;
    $univ_sched = json_decode($data, true);
    $data       = array_filter($univ_sched,array($f,"filter"));
    print_r($data);
}

这篇关于PHP array_filter用争论回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆