在 PHP 中将 stdClass 对象转换为数组 [英] Convert stdClass object to array in PHP
本文介绍了在 PHP 中将 stdClass 对象转换为数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我从 postmeta 中获取 post_id 为:
I fetch post_id from postmeta as:
$post_id = $wpdb->get_results("SELECT post_id FROM $wpdb->postmeta WHERE (meta_key = 'mfn-post-link1' AND meta_value = '". $from ."')");
当我尝试 print_r($post_id);
我有这样的数组:
when i try print_r($post_id);
I have array like this:
Array
(
[0] => stdClass Object
(
[post_id] => 140
)
[1] => stdClass Object
(
[post_id] => 141
)
[2] => stdClass Object
(
[post_id] => 142
)
)
我不知道如何遍历它,我怎么能得到这样的数组
and i dont know how to traverse it, and how could I get array like this
Array
(
[0] => 140
[1] => 141
[2] => 142
)
知道我该怎么做吗?
推荐答案
最简单的方法是对对象进行 JSON 编码,然后将其解码回数组:
The easiest way is to JSON-encode your object and then decode it back to an array:
$array = json_decode(json_encode($object), true);
或者,如果您愿意,也可以手动遍历对象:
Or if you prefer, you can traverse the object manually, too:
foreach ($object as $value)
$array[] = $value->post_id;
这篇关于在 PHP 中将 stdClass 对象转换为数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文