在 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;