从具有特定属性值的对象获取值

时间:2018-07-06 20:57:47

标签: php

我得到的输出是用户成员资格的集合。我需要过滤输出,以便得到'mon_id',其中u_id等于req_uid aka 13,同时g_id等于req_grp aka 4。

 $req_uid=13;
$req_grp=4;

$output={"main_id":"dcb912dcb912"}{
"7":[{"mon_id":14,"g_id":1,"u_id":7}],
"1":[{"mon_id":1,"g_id":1,"u_id":1}, {"mon_id":2,"g_id":2,"u_id":1}],
"4":[{"mon_id":7,"g_id":1,"u_id":4},{"mon_id":32,"g_id":2,"u_id":4}],
"13":[{"mon_id":28,"g_id":1,"u_id":13},{"mon_id":29,"g_id":4,"u_id":13}],
"6":[{"mon_id":13,"g_id":1,"u_id":6}],"12":[{"mon_id":22,"g_id":1,"u_id":12}],
"2":[{"mon_id":3,"g_id":1,"u_id":2},{"mon_id":31,"g_id":2,"u_id":2},{"mon_id":33,"g_id":4,"u_id":2}],
"9":[{"mon_id":16,"g_id":1,"u_id":9}],
"5":[{"mon_id":11,"g_id":1,"u_id":5},{"mon_id":12,"g_id":2,"u_id":5}],
"10":[{"mon_id":18,"g_id":1,"u_id":10}],
"8":[{"mon_id":15,"g_id":1,"u_id":8}]
}


$myjson = json_decode($output, true);
foreach($myjson as $key => $value){
    //filter...
}

1 个答案:

答案 0 :(得分:0)

顶级JSON输出是一个将用户ID映射到订阅列表的对象。因此,您可以遍历订阅列表,然后选择与您的搜索条件相匹配的列表:

$reqUid = 13;
$reqGrp = 4;
$monIds = array();

foreach ($userSubscriptions as $userId => $subscriptions) {
    foreach ($subscriptions as $subscription) {
        if ($subscription['u_id'] == $reqUid && $subscription['g_id'] == $reqGrp) {
            $monIds[] = $subscription['mon_id'];
        }
    }
}

print('Found ' + count($monIds) + ' matching mon_id values');