Homer_J
Homer_J

Reputation: 3323

MySQLi - search through an array

I have the following code:

function resultToArray($result) {
    $rows = array();
    while($row = $result->fetch_assoc()) {
        $rows[] = $row;
    }
    return $rows;
}

// Usage
$query = 'SELECT q17, COUNT(q17) FROM tresults GROUP BY q17';
$result = $mysqli->query($query);
$rows = resultToArray($result);
//print_r($rows); // Array of rows
$result->free();

Brings back the following (only an excerpt):

Array ( [0] => Array ( [q17] => [COUNT(q17)] => 7 ) [1] => Array ( [q17] => Admin & Clerical [COUNT(q17)] => 118 )......etc.

What I am struggling with is how to then return the data, basically, what I need is some code to pull out the data as follows:

WHERE Array = Admin & Clerical BRING BACK THE COUNT(q17) number

How do I search through the array, normally, I'd use something like:

if($rows['q17']==$q[$i]){echo$rows['COUNT(q17)'];}

But this doesn't work - I assume because there are two sets of data within each part of the array? Not sure how to deal with this.

Upvotes: 0

Views: 571

Answers (2)

Meti
Meti

Reputation: 365

You can achieve this by using MYSQL itself, by using HAVING clause instead of WHERE. To do this rewrite your query like this.

$query = 'SELECT q17, COUNT(q17) as qcount FROM tresults GROUP BY q17 HAVING q17="Admin & Clerical" ';

echo $row[0]['qcount']; //return  118

if you still want to it with PHP after getting the result from the database, it's how it done:

function get_q17_count($rows, $q17){
    foreach ($rows as $onerow) {
        if($onerow['q17'] == $q17){
            return $onerow['COUNT(q17)'];
        }
    } 
}

Upvotes: 1

Homer_J
Homer_J

Reputation: 3323

function resultToArray($results) {
    $rows = array();
    while($row = $results->fetch_assoc()) {
        $rows[] = $row;
    }
    return $rows;
}

// Usage
$querys = 'SELECT q17, COUNT(q17) FROM tresults GROUP BY q17';
$results = $mysqli->query($querys);
$rows = resultToArray($results);
//print_r($rows); // Array of rows
$results->free();

function searchForId($id, $array) {
   foreach ($array as $key => $val) {
       if ($val['q17'] === $id) {
           return $val['COUNT(q17)'];
       }
   }
   return null;
}

Called the function using:

    $id = searchForId($q[$i], $rows);echo " (".$id.")";

Upvotes: 0

Related Questions