开发者

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
   开发者_Python百科         [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.


$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'];


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

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜