Reputation: 329
My array coming like this
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
when i write like this
$myposts = get_posts( $args );
$arrDt = (array) $myposts;
print_r($arrDt);
but my problem is how can i get the values inside that object array.
please help. Thnx print_r($arrDt);
Upvotes: 5
Views: 12998
Reputation: 1317
In my case it was:
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;
}
Upvotes: 1
Reputation:
you can use wp_get_recent_posts() instead of get_posts(). The wp_get_recent_posts() function returns a normal array instead of object array, then by using foreach loop you can access any value of an array.
Upvotes: 0
Reputation: 327
It's very simple:
You have an Array Array ( [0] => stdClass Object ( [ID]
This array have one KEY, that can be identified by the "[0]" (but more keys may exist)) Accessing the key:
foreach ( $arrDt as $value ): //Look, whe are inside the first key. (currently is '0').
echo $value->ID;
echo $value->post_author;
endforeach;
Or, if you want to convert object to array ( like $value['ID'], for example ), you just needs this:
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);
Upvotes: 3
Reputation: 817228
It is just normal object access:
$obj = $arrDt[0];
echo $obj->ID;
echo $obj->post_author;
// etc.
But it depends on what you want to do. I suggest to have a look at the get_posts
examples. They use setup_postdata
to load the post content in the current context. If you want to display the post, this is probably the cleaner solution.
Upvotes: 5