开发者

Ignore empty iterations in a PHP array

开发者 https://www.devze.com 2023-02-01 15:36 出处:网络
I\'m trying to eliminate some items开发者_如何学JAVA in an array by checking some other profile information in the database matching the user id\'s.

I'm trying to eliminate some items开发者_如何学JAVA in an array by checking some other profile information in the database matching the user id's.

function filterSexMatches($sSex, $aMatchIds){
    foreach($aMatchIds as $iMatchId){
        $aMatches[] = $this->getOne("SELECT `ID` FROM `Profiles` WHERE `ID` = '{$iMatchId}' AND `Sex` != '{$sSex}'");           
    }
    return $aMatches;
}

This is my function but it returns an empty id value when the Sex doesn't match and adds it to the $aMatches array.

I want to know how I can change this to skip over the user id if the Sex field matches so it doesn't return an empty iteration.


function filterSexMatches($sSex, $aMatchIds){
    $aMatches = array();
    foreach($aMatchIds as $iMatchId){
        $data = $this->getOne("SELECT `ID` FROM `Profiles` WHERE `ID` = '{$iMatchId}' AND `Sex` != '{$sSex}'");           
        if (!empty($data)) {
            $aMatches[] = $data;
        }
    }
    return $aMatches;
}


Personally I would use a single query to get all profiles and then iterate over the result in php, matching and adding to an empty array. Instead of executing a single query for every id.

Not exactly sure how you're system works but I'll try to give ex.

$result = $this->getOne("SELECT * FROM Profiles WHERE ... ");

$newArray = array();
foreach($result as $row) {
    if($row->sex == $sSex) {
        $newArray[] = $row;
    }
}
return $newArray;
0

精彩评论

暂无评论...
验证码 换一张
取 消