php数组键=>值搜索

您好,我是PHP的新手.

我有一个数组

$arr = array(0 => array(‘GID’=> 1,’groupname’=>“ cat1”,’members’=> array(0 => array(‘mid’=> 11 ,’mname’=>’wwww’),1 => array(‘mid’=> 12,’mname’=>’wswww’))),
             1 => array(‘GID’=> 2,’groupname’=>“ cat2”,’members’=> array(0 => array(‘mid’=> 13,’mname’=>’gggwwww ‘),1 => array(‘mid’=> 14,’mname’=>’wvvwww’))),
             2 => array(‘GID’=> 3,’groupname’=>“ cat1”,’members’=> array(0 => array(‘mid’=> 15,’mname’=>’wwddsww ‘)),1 => array(‘mid’=> 16,’mname’=>’wwwdddw’))));

      ie...,I have GID,groupname,mid(member id),mname(member name).I want to insert a new mid and mname into a group if it is already in the array ,if it is not exists then create a new subarray with these elements..I also need to check a member id(mid) is also present.........................I used the code but its not working fine............. if (!empty($evntGroup)) {


            foreach ($evntGroup as $k => $group) {

                if ($group['GID'] == $group_id) {
                    foreach($group as $j=> $mem){

                    if($mem['mid'] == $mem_id){

                        unset($evntGroup[$k]['members'][$j]['mid']);
                        unset($evntGroup[$k]['members'][$j]['mname']);
                    }
                    else{


                    $evntGroup[$k]['members'][] = array(
                        'mid' => $mem_id,
                        'mname' => $mem_name);

                    }}
                } else {


                    $evntGroup[] = array(
                        'GID' => $group_id,
                        'groupname' => $Group['event_group_name'],
                        'members' => array(
                            0 => array(
                                'mid' => $mem_id,
                                'mname' => $mem_name
                            )
                        )
                    );

                }

            }
        } else {

            $evntGroup[$i]['GID'] = $group_id;
            $evntGroup[$i]['groupname'] = $Group['event_group_name'];
            $evntGroup[$i]['members'][] = array(
                'mid' => $mem_id,
                'mname' => $mem_name);
            $i++;

        }

解决方法:

函数的形式,最简单的解决方案如下所示:

function isgidInArray($arr, $val) {
    foreach($arr as $cur) {
        if($cur['GID'] == $val)
            return true;
    }
    return false;
}

您已经更新了问题,以指定在找到指定的GID时要执行的操作,但这只是对循环的一个微不足道的补充:

function doSomethingIfGidInArray($arr, $val) {
    foreach($arr as $cur) {
        if($cur['GID'] == $val) {
            doSomething();
            break; //Assuming you only expect one instance of the passed value - stop searching after it's found
        }
    }
}

不幸的是,没有原生的PHP数组函数可以检索父数组中每个数组的相同索引.我经常想要这样的东西.

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...