Php 如何将对象转换为数组以获取数据?
我的阵型是这样的Php 如何将对象转换为数组以获取数据?,php,wordpress,Php,Wordpress,我的阵型是这样的 Array ( [0] => stdClass Object ( [ID] => 578 [post_author] => 1 [post_date] => 2011-01-18 07:23:17 [post_date_gmt] => 2011-01-18 07:23:17 [post_content] => Home WordPress is web software you can use to create a beautiful we
Array ( [0] => stdClass Object ( [ID] => 578 [post_author] => 1 [post_date] => 2011-01-18 07:23:17 [post_date_gmt] => 2011-01-18 07:23:17 [post_content] => Home WordPress is web software you can use to create a beautiful website or blog. We like to say that WordPress is both free and priceless at the same time. The core software is built by hundreds of community volunteers, and when you’re ready for more there are thousands of plugins and themes available to transform your site into almost anything you can imagine. Over 25 million people have chosen WordPress to power the place on the web they call “home” — we’d love you to join the family [post_title] => second post [post_excerpt] => [post_status] => publish [comment_status] => open
当我这样写的时候
$myposts = get_posts( $args );
$arrDt = (array) $myposts;
print_r($arrDt);
但我的问题是如何获取该对象数组中的值
请帮忙。
Thnx
印刷费($arrDt) 这只是普通的对象访问:
$obj = $arrDt[0];
echo $obj->ID;
echo $obj->post_author;
// etc.
但这取决于你想做什么。我建议看一下这些例子。他们使用setup\u postdata
在当前上下文中加载帖子内容。如果您想显示帖子,这可能是更干净的解决方案。非常简单:
您有一个数组数组([0]=>stdClass对象([ID]
此数组有一个键,可由“[0]”标识(但可能存在更多键))
访问密钥:
foreach ( $arrDt as $value ): //Look, whe are inside the first key. (currently is '0').
echo $value->ID;
echo $value->post_author;
endforeach;
或者,如果您想将对象转换为数组(例如$value['ID']),您只需要:
function objectToArray($obj)
{
if (is_object($obj)):
$object = get_object_vars($obj);
endif;
return array_map('objectToArray', $object); // return the object, converted in array.
}
$objArray = objectToArray($arrDt);
print_r($objArray);
您可以使用wp\u get\u recent\u posts()而不是get\u posts()。wp\u get\u recent\u posts()函数返回一个普通数组而不是对象数组,然后通过使用foreach循环,您可以访问数组的任何值。在我的例子中:
foreach ($returnedObject as $row) {
$sub_array = '';
$sub_array['ID'] = $row->data->ID;
$sub_array['user_login'] = $row->data->user_login;
$sub_array['display_name'] = $row->data->display_name;
$sub_array['user_email'] = $row->data->user_email;
$sub_array['user_registered'] = $row->data->user_registered;
$main_array[] = $sub_array;
}
@用户如果回答了你的问题,鼓励你接受它旁边的绿色勾划大纲勾画它。如果有多个答案,勾选一个对你最有帮助,并考虑赞成任何其他答案。