Codeigniter - 访问多维stdObject数组时出错

时间:2013-10-27 14:49:14

标签: php codeigniter

我从CodeIgniter中的控制器获取以下结果数组:

Array
(
    [cities] => Array
    (
        [0] => stdClass Object
        (
            [id] => 1
            [name] => Jersey City
            [state] => stdClass Object
            (
                [id] => 1
                [name] => New Jersey             
            )
         )

        [1] => stdClass Object
        (
            [id] => 2
            [name] => Philadelphia
            [state] => stdClass Object
            (
                [id] => 2
                [name] => Pennsylvania
            )
        )
    )
)

现在我想创建一个包含这些值的下拉框,以便该框具有city,state。

Jersey, New Jersey
Philadelphia, Pennsylvania

这就是我想要实现的目标:

<?php 
    foreach($cities as $city) {
        echo "<option value='$city->id'>$city->name, $city->state->name</option>";
    }
?>

当我尝试访问时:

$city->state->name

我收到以下错误:

<p>Severity: 4096</p>
<p>Message: Object of class stdClass could not be converted to string</p>

如果有人能指导我从状态数组中获取名称的正确方法,我将不胜感激。

谢谢!

2 个答案:

答案 0 :(得分:1)

您正在处理一个对象,但是当您echo它时,PHP会尝试将其转换为字符串并失败,从而生成上述错误消息。为避免这种情况,您可以将变量包装在花括号{ }中,如下所示:

foreach($cities as $city) { 
    echo "<option value='{$city->id}'>{$city->name}, 
    {$city->state->name}</option>"; 
} 

或者,您也可以使用sprintf()(在我看来,它更干净一点):

foreach($cities as $city) { 
    echo sprintf("<option value='%d'>%s, %s</option>", 
    $city->id, $city->name, $city->state->name); 
}

答案 1 :(得分:0)

试试这个:

foreach($cities as $city) {
    foreach($city->state as $state) {
        echo "<option value='$city->id'>$city->name, $state->name</option>";
    }
}

或试试这个:

foreach($cities as $city) {
        echo "<option value='$city->id'>$city->name, $city->state[0]->name</option>";
    }