2

我从 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
            )
        )
    )
)

现在我想用这些值创建一个下拉框,以便该框具有城市、州。

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>

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

谢谢!

4

2 回答 2

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); 
}
于 2013-10-27T16:00:25.810 回答
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>";
    }
于 2013-10-27T14:51:15.723 回答