PHP - 从数组中获取值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2526084/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 06:49:42  来源:igfitidea点击:

PHP - Get values from Array

phparrays

提问by CLiown

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?

回答by animuson

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 对象的数组,而不是另一个数组。

回答by Tesserex

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[1]->subjectid

回答by Dan

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

$opt 是一个行数组。所以你会做这样的事情:

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

Or just use an index:

或者只使用索引:

$opt[0]['subjectid'];