我有一个循环的对象数组,并且一个公共属性不断导致CodeIgniter发出通知错误。从我读到的,'州'在PHP中不是保留字。部分对象转储
array (size=1)
0 =>
object(stdClass)[15]
public 'ID' => int 107292435 (length=9)
public 'RegTypeID' => int 1172891 (length=7)
public 'StatusID' => int 2 (length=2)
public 'City' => string 'Philadelphia' (length=7)
public 'State' => string 'PA' (length=2)
...
当我遍历每个对象进行输出时,如下所示
foreach ($attendees as $attendee):
echo "<tr><td>{$attendee->Title}</td>\n";
echo "<td>{$attendee->Company}</td>\n";
echo "<td>{$attendee->State}</td>\n";
echo "<td>{$attendee->Country}</td></tr>\n";
endforeach;
严重程度:通知 消息:未定义的属性:stdClass :: $ State
我尝试使用索引值$attendee->{'4'}
输出,但也失败了。我想避免循环并添加另一个属性名称,以便在可能的情况下替换此属性。
添加print_r结果,例如:
stdClass Object
(
[ID] => 108279742
[EventID] => 2148055
[FirstName] => Bob
[LastName] => Smith
[Company] => AbbVie
[Title] => Sample Title
[State] => IL
[Country] => United States
)
答案 0 :(得分:2)
您可能在所有记录中都没有State
属性。
你可以做的是填写之前或使用if语句检查并输出一些默认信息,如下所示:
echo "<td>". (isset($attendee->State)? $attendee->State : "no info available"). "</td>\n"
答案 1 :(得分:0)
我的环境是php 7.1和codeigniter 3.1.8
我在我的测试控制器中创建了以下函数用于测试目的,并且State输出没有错误消息。
public function func(){
$attendee=new stdClass;
$attendee->ID=107292435;
$attendee->RegTypeID=1172891;
$attendee->StatusID=2;
$attendee->Title='Michael Jackson';
$attendee->Company='Worlds Best Music Stars';
$attendee->City='Philadelphia';
$attendee->State='PA';
$attendee->Country='USA';
$attendees=array();
$attendees[]=$attendee;
foreach ($attendees as $attendee){
echo "<tr><td>{$attendee->Title}</td>\n";
echo "<td>{$attendee->Company}</td>\n";
echo "<td>{$attendee->State}</td>\n";
echo "<td>{$attendee->Country}</td></tr>\n";
}
}
输出如下:
<tr><td>Michael Jackson</td>
<td>Worlds Best Music Stars</td>
<td>PA</td>
<td>USA</td></tr>