tmartin314
tmartin314

Reputation: 4171

Ignore empty iterations in a PHP array

I'm trying to eliminate some items 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.

Upvotes: 0

Views: 300

Answers (2)

webbiedave
webbiedave

Reputation: 48887

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;
}

Upvotes: 1

jondavidjohn
jondavidjohn

Reputation: 62402

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;

Upvotes: 0

Related Questions