问:我写了一个返回对象的 sql 查询。在我的视图文件中使用了该对象后,我现在需要将它转换为一个数组,以便我可以删除重复的条目。
要将对象转换为数组,我正在使用,
$arr = (array)$object_name;
这是结果。
Array
(
[0] => stdClass Object
(
[id] => 1
[body_parts_id] => 2
[conditions_id] => 1
[priorities_id] => 1
[name_of_body_part] => Lungs and airways
[name_of_condition] => Unconscious, not breathing or responding.
[priority_title] => Priority One
)
[1] => stdClass Object
(
[id] => 1
[body_parts_id] => 1
[conditions_id] => 1
[priorities_id] => 1
[name_of_body_part] => Heart and blood vessels
[name_of_condition] => Unconscious, not breathing or responding.
[priority_title] => Priority One
)
[2] => stdClass Object
(
[id] => 1
[body_parts_id] => 1
[conditions_id] => 2
[priorities_id] => 1
[name_of_body_part] => Heart and blood vessels
[name_of_condition] => Signs of a heart attack
[priority_title] => Priority One
)
[3] => stdClass Object
(
[id] => 1
[body_parts_id] => 1
[conditions_id] => 3
[priorities_id] => 1
[name_of_body_part] => Heart and blood vessels
[name_of_condition] => Heavy bleeding that won't stop
[priority_title] => Priority One
)
[4] => stdClass Object
(
[id] => 2
[body_parts_id] => 3
[conditions_id] => 4
[priorities_id] => 2
[name_of_body_part] => Muscle, bone and joint
[name_of_condition] => Condition test 1
[priority_title] => Priority Two
)
)
当我尝试现在循环遍历数组以删除任何重复时,问题就来了。我得到消息。
不能将 stdClass 类型的对象用作数组
显然我没有正确地将对象转换为数组。
有人可以帮忙吗-谢谢。
答:要将对象转换为数组,您应该更改
$arr = (array)$object_name;
为此
$arr = json_decode($object_name, true);