数组搜索key =>值

时间:2012-12-06 06:52:45

标签: php

我有一个数组,

$arr=(
    [0] => Array
        (
            [groupid] => 1
            [groupname] => Red
            [members] => Array
                (
                    [0] => Array
                        (
                            [mid] => 9
                            [name] => Anith
                        )

                    [1] => Array
                        (
                            [mid] => 11
                            [name] => Aravind
                        )

                    [2] => Array
                        (
                            [mid] => 10
                            [name] => Lekshmi
                        )



                )

        )

    [1] => Array
        (
            [groupid] => 2
            [groupname] => Blue
            [members] => Array
                (
                    [0] => Array
                        (
                            [mid] => 6
                            [name] => Yamuna
                        )

                    [1] => Array
                        (
                            [mid] => 2
                            [name] => Kamala K
                        )

                    [2] => Array
                        (
                            [mid] => 13
                            [name] => Sooraj K
                        )



                )

        )

我想检查数组中的[mid] => 2 ..如果它存在 我想删除它(即取消设置数组)-----

[1] => Array
                        (
                            [mid] => 2
                            [name] => Kamala K
                        )
;;;

例如: - unset($arr[1]['members'][2];

1 个答案:

答案 0 :(得分:4)

这应该可以解决问题

foreach ($arr as $group => $subarray) {
    foreach ($subarray['members'] as $k => $v) {
        if ($v['mid'] == 2) {
            unset($arr[$group]['members'][$k]);
            break;
        }
    }
}

var_dump($arr);

如果你想变得狡猾,你可以这样做:

// note: requires PHP >= 5.3
foreach ($arr as $key => &$value) {
    $value['members'] = array_filter(
        $value['members'],
        function($member) {
           return $member['mid'] != 2;
        }
    );
}

var_dump($arr);