2011-01-22 67 views
5

我的陣列來這樣如何將對象轉換爲數組以獲取數據?

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 print_r($ arrDt);

回答

4

這只是正常的對象訪問:

$obj = $arrDt[0]; 
echo $obj->ID; 
echo $obj->post_author; 
// etc. 

但是這取決於你想要做什麼。我建議看看get_posts的例子。他們使用setup_postdata加載當前上下文中的發佈內容。如果你想顯示帖子,這可能是更乾淨的解決方案。

+0

喔,我的上帝謝謝費利克斯ü解決我的問題日Thnx日Thnx – rajeshrt 2011-01-22 11:45:58

3

這很簡單:

您有一個陣列Array ([0] => stdClass Object ([ID]

該數組具有一個KEY,可以由「[0]」(但更多的鍵可能存在的)) 訪問鍵被識別:

foreach ($arrDt as $value): //Look, whe are inside the first key. (currently is '0'). 
    echo $value->ID; 
    echo $value->post_author; 
endforeach; 

或者,如果你想對象轉換爲數組(如$值 '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); 
0

您可以使用wp_get_recent_posts()而不是get_posts()wp_get_recent_posts()函數返回一個普通數組而不是對象數組,然後通過使用foreach循環可以訪問數組的任何值。

1

在我的情況是:

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