简体   繁体   中英

PHP - Get values from Array

I am trying to retrieve a value from an Array. Here is the code:

$opt=get_records_sql($sql1);

print_object($opt);

$n = count($opt);
if (empty($opt)){
    echo 'No options selected';
}
else{
    $optno = $opt["subjectid"];
    echo '<br>$optno = '.$optno;
}

I tried to use: $opt["subjectid"] but I get the following error:

Notice: Undefined index: subjectid

Contents of array:

Array
(
    [1] => stdClass Object
        (
            [uname] => JHollands06
            [tutor] => M LSt
            [subjectid] => 1
            [year] => 2010
            [optid] => 1
        )

)

How to I fetch the data subjectid which has value 1?

Method 1: Convert the object to an array by casting it.

$opt[1] = (array) $opt[1];
echo $opt[1]['subjectid'];

To convert all objects in an array (if there are more than one):

foreach ($opt as $k => $val) {
    $opt[$k] = (array) $val;
}

Method 2: Simply call it as an object like it is already assigned.

echo $opt[1]->subjectid

There is a difference between an array and an object. An object contains variables that have to be called using the '->' and an array contains values which are associated with a specific key. As your output states, you have an array containing an stdClass object, not another array.

Your array contains rows. It's not just one row. So you need to index it by row first.

edit: your rows are objects, my bad. So it should be

$opt[1]->subjectid

$opt is an array of rows. So you'd do something like this:

foreach($opt as $row)
{
   echo $row['subjectid'];
}

Or just use an index:

$opt[0]['subjectid'];

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