解决从 PHP 中的调用返回的关联数组元素时遇到问题
Trouble Addressing Associate Array element returned from call in PHP
我想使用 return 从 api 调用的关联数组元素来与这样的字符串值进行比较:
<!-- Check If there are any todo items. If not skip Todo list markup. =====-->
<?php
if ($todo_items['todo_id'] == '1234567') {
//This value indicates no todo items for person
}
else {
//markup to render todo item list
?>
这会导致第 80 行的 /var/www/todo_client/todo.php 中的未定义索引:todo_id。
我输入 var_dump($todo_items) 结果是:
array (size=1)
0 =>
object(stdClass)[3]
public 'todo_id' => string '1234567' (length=7)
有谁知道为什么我无法访问 $todo_items['todo_id']?
您从 API 收到一组 stdClasses,因此如果您只有一个项目返回,您可以执行类似这样的操作来测试值:
$result = $todo_items[0];
if ($result->todo_id == '1234567') {/*...*/}
当返回(或可能)多个项目时,您可以遍历数组 ($todo_items
) 并对其中的每一个进行此测试:
foreach($todo_items as $item) {
if ($result->todo_id == '1234567') {/*...*/}
}
我想使用 return 从 api 调用的关联数组元素来与这样的字符串值进行比较:
<!-- Check If there are any todo items. If not skip Todo list markup. =====-->
<?php
if ($todo_items['todo_id'] == '1234567') {
//This value indicates no todo items for person
}
else {
//markup to render todo item list
?>
这会导致第 80 行的 /var/www/todo_client/todo.php 中的未定义索引:todo_id。 我输入 var_dump($todo_items) 结果是:
array (size=1)
0 =>
object(stdClass)[3]
public 'todo_id' => string '1234567' (length=7)
有谁知道为什么我无法访问 $todo_items['todo_id']?
您从 API 收到一组 stdClasses,因此如果您只有一个项目返回,您可以执行类似这样的操作来测试值:
$result = $todo_items[0];
if ($result->todo_id == '1234567') {/*...*/}
当返回(或可能)多个项目时,您可以遍历数组 ($todo_items
) 并对其中的每一个进行此测试:
foreach($todo_items as $item) {
if ($result->todo_id == '1234567') {/*...*/}
}