场景:

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

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

有帮助吗?

解决方案

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

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

可以找到更多信息和示例此处

其他提示

如果我理解正确,您应该能够遵循常规对象语法来获得所需的结果。将可选的第二个参数添加到 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对象。

SPL ArrayObject 让我们使用与您的示例中生成错误相同的语法。如果您能够使用 ArrayObject 而不是 stdClass

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top