简体   繁体   中英

Return array result from query from function

Hi all I'm new to oop and I wanted to find out how to return multiple array variable from a function. Please see below for an explanation

function getvalues(){
  //do mysql query using pdo
   while($row = $getmostvalues->fetch(PDO::FETCH_ASSOC)) {
        $value[] = $row['val1'];
        $time[] = $row['time'];

    }


}

how can I retrieve and use say $value[0] in my php code after calling getvalues();

The problem you're looking for an answer on doesn't have anything to do with OOP, but here's your answer. It's more of a question on how to use arrays.

function getvalues(){
    while($row = $getmostvalues->fetch(PDO::FETCH_ASSOC)) {
        $value[] = $row['val1'];
        $time[] = $row['time'];
    }

    return array($value,$time);
}

$retval = getvalues();
$arrValues = $retval[0];
$arrTimes = $retval[1];

Value at index of the values array would then be $arrValues[0] .

If you're trying to return an object:

return (object) array('value' => $value, 'time' => $time);

This would return an object with two arrays accessible via $retval->value and $retval->time

If you don't want arrays, cast those arrays as objects as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM