[英]Trying to get property of non-object when trying to access array
I'm trying to access a array via its index, but I need to get this from the query string. 我正在尝试通过其索引访问数组,但是我需要从查询字符串中获取它。
I've tried: 我试过了:
$var = $_GET['id'];
echo $xml->subway->line[$var]->name;
That doesn't work. 那不行 But this does:
但这确实是:
echo $xml->subway->line[0]->name;
try this: 尝试这个:
$var = isset($_GET['id']) ? (int)$_GET['id'] : false;
if ($var !== false && isset($xml->subway->line[$var]) {
echo $xml->subway->line[$var]->name;
} else {
echo 'Your problem is either "id" not being in $_GET or $xml object does not have line with that index';
var_dump($_GET); //see what is 'id'
}
Everytime you are getting item from an array by index you should check if it is set first to avoid errors like this. 每次从索引数组中获取项目时,都应检查是否首先设置了该项目,以避免出现此类错误。
It's likely that your $_GET
variable is coming back as a string
instead of an integer
so PHP will be assuming the index doesn't exist. 您的
$_GET
变量很可能以string
而不是integer
因此PHP将假定索引不存在。 Try type casting it as 尝试将其强制转换为
$var = (int)$_GET['id'];
Which forces PHP to treat the $_GET
as an integer
这迫使PHP将
$_GET
视为integer
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.