我对php很新。
我有一个数组
$ arr = array(0 => array('GID'=> 1,'groupname'=>“cat1”,'members'=> array(0 => array('mid'= > 11, 'MNAME'=> 'WWWW'),1 =>阵列( '中'=> 12, 'MNAME'=> 'wswww'))), 1 =>阵列( 'GID'=大于2, '组名'=> “中CAT2”, '成员'=>阵列(0 =>阵列( '中'=> 13, 'MNAME'=>'gggwwww '),1 =>阵列(' 中 '=> 14,' MNAME '=>' wvvwww'))), 2 =>阵列( 'GID'=→3 '组名'=> “中CAT1”, '成员'=>阵列(0 =>阵列( '中'=→15 'MNAME'=>'wwddsww ')),1 =>阵列(' 中 '=> 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++;
}
答案 0 :(得分:2)
以函数的形式,最简单的解决方案将如下所示:
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数组函数可以检索父数组中每个数组的相同索引。我经常想要这样的东西。
答案 1 :(得分:1)
像这样的东西将匹配GOD等于3:
foreach( $arr as $item ) {
if( $item['GID'] == 3 ) {
// matches
}
}
答案 2 :(得分:1)
有代码
function updateByGid(&$array,$gid,$groupname,$mid,$mname) {
//For each element of the array
foreach ($array as $ii => $elem) {
//If GID has the same value
if ($elem['GID'] == $gid) {
//Insert new member
$array[$ii]['members'][]=array(
'mid'=>$mid,
'mname'=>$mname);
//Found!
return 0;
}
}
//If not found, create new
$array[]=array(
'GID'=>$gid,
'groupname'=>$groupname,
'members'=>array(
0=>array(
'mid'=>$mid,
'mname'=>$mname
)
)
);
return 0;
}