在数组上使用 str_replace
我有一个问题,我似乎无法找到解决方案。在 foreach 循环中,
foreach( $results->result as $item )
以下代码
$item->title = str_replace( " - Home", "", $item->title );
总是抛出错误
可捕获的致命错误:stdClass 类的对象无法转换为字符串
我认为 str_replace
能够处理数组?为了使其正常工作,我需要改变什么?
感谢您的任何建议!
I've got a problem which I can't seem to find a solution to. In a foreach loop
foreach( $results->result as $item )
the following code
$item->title = str_replace( " - Home", "", $item->title );
always throws an error
Catchable fatal error: Object of class stdClass could not be converted to string
I thought str_replace
was able to handle arrays? What would I need to change in order to get this working?
Thanks for any advice!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
它不是一个数组,而是一个对象,正如错误所述...您是否有机会使用
json_decode()
获得它?然而,解决方案很简单 - 将其转换为数组:
另一点是,如果您想要修改
$results->result
中保存的数据,而不仅仅是它的副本,您将需要您的foreach
为:...并获取项目作为参考,而不是副本...
It's not an array, it's an object, as the error says... did you get it with
json_decode()
by any chance?However, the solution is simple - cast it to an array:
Another point about this is that if you are wanting to modify the data held in
$results->result
, and not just a copy of it, you will need yourforeach
to be:...and get item as a reference, not a copy...
$item->title
似乎是stdClass
类型的对象,而不是字符串。执行var_dump($item->title)
查看对象的外观。另外,您的循环不会执行您期望的操作,循环完成后,
$results->result
中的所有对象仍将具有相同的值(使用foreach($results- >结果为 &$item)
(通过引用传递))$item->title
seems to be an object of typestdClass
, and not a string. Dovar_dump($item->title)
to see what the object looks like.Also, you loop won't do what you expect, after the loop has finished, all objects in
$results->result
will still have the same values (useforeach($results->result as &$item)
(pass by reference))对
$item->title
执行var_dump
,因为它不是数组,而是对象。str_replace
只能处理实际的数组和字符串。如果您希望这是一个数组,那么您可能在其他地方遇到一些问题,我会对此进行研究。如果您只是在寻找补丁,那么您也许可以通过投射它来逃脱惩罚。如果其他一切正常,我会这样做,因为它确实具有最少的副作用:
如果
title
必须是一个数组,那么您可以在没有(object)
,但我认为最好追踪title
的设置位置并确保值正确。顺便说一句 - 如果您计划在循环之外使用
$item->title
,您还需要确保您使用的是引用,以便项目本身得到更新:Do a
var_dump
on$item->title
, because it isn't an array, it is an object.str_replace
can only handle actual arrays and strings. If you're expecting this to be an array, then you might have some problems elsewhere and I would look into that.If you're just looking for a patch, you might be able to get away with casting it. If everything else is working, I would do this because it really has the fewest side-effects:
If
title
has to be an array, you can get away without the(object)
, but I think it would be a better idea to track down wheretitle
is being set and have the value correct to begin with.BTW — if you're planning on using
$item->title
outside of the loop, you also need to make sure you are using a reference so that the item itself is updated: