Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
86 views
in Technique[技术] by (71.8m points)

php - How to filter a two dimensional array by value

How would I create a function that filters a two dimensional array by value?

Given the following array :

Array
(
    [0] => Array
        (
            [interval] => 2014-10-26
            [leads] => 0
            [name] => CarEnquiry
            [status] => NEW
            [appointment] => 0
        )

    [1] => Array
        (
            [interval] => 2014-10-26
            [leads] => 0
            [name] => CarEnquiry
            [status] => CALL1
            [appointment] => 0
        )

    [2] => Array
        (
            [interval] => 2014-10-26
            [leads] => 0
            [name] => Finance
            [status] => CALL2
            [appointment] => 0
        )

    [3] => Array
        (
            [interval] => 2014-10-26
            [leads] => 0
            [name] => Partex
            [status] => CALL3
            [appointment] => 0
        )

How would I filter the array to only show those arrays that contain a specific value in the name key? For example name = 'CarEnquiry'.

The resulting output would be:

Array
(
    [0] => Array
        (
            [interval] => 2014-10-26
            [leads] => 0
            [name] => CarEnquiry
            [status] => NEW
            [appointment] => 0
        )

    [1] => Array
        (
            [interval] => 2014-10-26
            [leads] => 0
            [name] => CarEnquiry
            [status] => CALL1
            [appointment] => 0
        )

    )

EDIT

I forgot to mention that the search value should be interchangeable - i.e. name = 'CarEnquiry' or name = 'Finance'.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use PHP's array_filter function with a callback.

$new = array_filter($arr, function ($var) {
    return ($var['name'] == 'CarEnquiry');
});

Edit: If it needs to be interchangeable, you can modify the code slightly:

$filterBy = 'CarEnquiry'; // or Finance etc.

$new = array_filter($arr, function ($var) use ($filterBy) {
    return ($var['name'] == $filterBy);
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...