我正在建立一個目錄網站,並堅持要讓foreach循環訪問多站點的博客ID。從代碼中的註釋中可以看到,對博客ID的查詢工作正常,print_r檢查顯示數組已填充,但是當函數到達第一個foreach時,循環每次都會返回相同的結果,而在foreach循環內的site_blog_id上的print_r顯示它是空的。在循環中手動設置site_blog_id可以讓代碼的其餘部分正常工作,所以它肯定是foreach處理數組的一些東西。無法通過foreach循環處理數組 - 請幫助嗎?
我非常疑惑,因爲這似乎與我在開發人員的網站上看到的數組foreach代碼的許多示例相同,包括查詢文檔頁上的代碼。我想知道是否需要使用site_blog_ids變量來保存數組,以使其與foreach一起工作,但坦率地說我卡住了。 任何幫助將不勝感激! 大衛
/* get all subsite blog ids */
global $wpdb;
$site_blog_ids = $wpdb->get_results($wpdb->prepare("SELECT blog_id FROM wp_blogs where blog_id > 1"));
print_r($site_blog_ids);
/* check output - shows "Array ([0] => stdClass Object ([blog_id] => 2) [1] => stdClass Object ([blog_id] => 3) [2] => stdClass Object ([blog_id] => 5)) ". Looks fine? */
/* loop to iterate through the ids and display info from each blog */
foreach($site_blog_ids AS $site_blog_id) {
print_r("siteid= ".$site_blog_id."</br>");
/* check output - this shows $site_blog_id is empty, no value. That's not right, should be each blog ID in turn from the site_blog_ids array. */
$oldblog = $wpdb->set_blog_id($site_blog_id);
/* sets the system to use the loop blog ID instead of the current one. Since site_blog_id is empty, this doesn't work so the rest of the code uses the current blog, not the intended one. */
global $post;
$first_posts = get_posts('p=1'); //get the first post
foreach ($first_posts AS $post) {
setup_postdata();
the_title();
the_excerpt();
the_content();
the_category();
}
}
/* Tell the $wpdb object to go back to using the current site */
$wpdb->set_blog_id($oldblog);
可能要標記爲PHP和正確格式的代碼。 – jn1kk 2012-02-15 15:47:25
將標記,但「正確格式」在這個網站上很難,所以我解決了可讀性。 – Dains 2012-02-15 17:34:25