PHP-从数组获取值 [英] PHP - Get values from Array

查看:74
本文介绍了PHP-从数组获取值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从数组中检索值。下面是代码:

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;
}

我尝试使用: $ opt [ subjectid ] ,但出现以下错误:

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

Notice: Undefined index: subjectid

数组内容:

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

)

如何获取值为1的数据主题?

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

推荐答案

方法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;
}

方法2:只需将其称为对象

echo $opt[1]->subjectid

数组和对象之间是有区别的。对象包含必须使用->调用的变量,而数组包含与特定键相关联的值。作为输出状态,您有一个包含stdClass对象的数组,而不是另一个数组。

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.

这篇关于PHP-从数组获取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆