PHP stdClass问题

时间:2009-10-25 06:20:15

标签: php stdclass

场景:

$x = json_decode( $x );
foreach ( $x as $item )
{
    $info[] = $item;  //ERROR
}

我正在循环数据Feed以获取数据。我想在循环中将项添加到stdClass对象。我该怎么办?我对stdobj并不熟悉。

3 个答案:

答案 0 :(得分:5)

如果您希望json_decode返回一个数组,您可以执行以下操作:

$x = json_decode( $x, true ); // returns associative array instead of object
$info = (object) $x;

可以找到更多信息和示例here

答案 1 :(得分:4)

如果我理解正确,您应该能够遵循常规对象语法来获得所需的结果。将可选的第二个参数添加到json_decode设置为true,以使您的json解码为关联数组,因为这似乎是您正在使用它的表单。

$info = new stdClass();
$x = json_decode( $x, true );
foreach ( $x as $key => $val) { 
    $info->$key = $val;
}

正如Ignas所指出的那样,json_decode()的结果已经作为stdClass对象返回,所以如果您刚刚使用$x = json_decode($x),则根本不需要$info。你已经有$x作为stdClass对象了。

答案 2 :(得分:1)

SPL的{​​{3}}让您使用与示例中生成错误相同的语法。如果您可以使用ArrayObject代替stdClass