简体   繁体   English

PHP - 从Array获取值

[英]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: 我试图使用: $opt["subjectid"]但是我收到以下错误:

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? 如何获取值为1的数据subjectid?

Method 1: Convert the object to an array by casting it. 方法1:通过强制转换对象将对象转换为数组。

$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. 方法2:简单地将其称为已分配的对象。

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. 正如您的输出所述,您有一个包含stdClass对象的数组,而不是另一个数组。

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. $ opt是一个行数组。 So you'd do something like this: 所以你会做这样的事情:

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

Or just use an index: 或者只使用索引:

$opt[0]['subjectid'];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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