tags:

views:

47

answers:

3

I am trying to get a record from a database using an sql lookup (sql1). This then returns as an array which is fine, but I need to use part of the array for my next stage.

$opt=get_records_sql($sql1);

    //Diags for SQL content
        print_object($opt);

    $n = count($opt);
    if (empty($opt))
        {
        echo 'No options selected';
        }
    else
        {

        $optno = $opt["subjectid"];

        // Diags of $optno
            echo '<br>$optno = '.$optno;

As you can see, I tried to use this: $opt["subjectid"] as subjectid is the fieldname that I am trying to access and I was under the impression that this was correct for accessing an array, but I get the following error:

Notice: Undefined index: subjectid

Array contents:

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

)
A: 

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

Tesserex
Get Fatal error: Cannot use object of type stdClass as array
danit
A: 

$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'];
Dan
+3  A: 

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.

animuson