2014-07-14 92 views
2

var_dump的變量$results的說明是這樣的提取值了stdClass的對象

array (size=11) 
    0 => 
    object(stdClass)[69] 
     public 'Tables_in_database-name-here' => string 'wp_commentmeta' (length=14) 
    1 => 
    object(stdClass)[68] 
     public 'Tables_in_database-name-here' => string 'wp_comments' (length=11) 
    2 => 
    object(stdClass)[67] 
     public 'Tables_in_database-name-here' => string 'wp_links' (length=8) 

    ... 

    10 => 
    object(stdClass)[59] 
     public 'Tables_in_database-name-here' => string 'wp_users' (length=8) 

我希望能在提取表名了上述的結構,並列出它們像這樣的逗號分隔形式;

`wp_commentmeta,wp_comments,wp_links....,wp_users` 

我得到了一個關於如何從這種結構中提取數據的腦凍結時刻。

我嘗試了很多選擇,因爲你可以通過下面的代碼來關注它 - 每個結尾的錯誤!

foreach ($results as $current_item): 
     /* 
     * $current_item is something like this: 
     * 
     * object(stdClass)[69] 
      public 'Tables_in_database-name-here' => string 'wp_commentmeta' (length=14) 
     */ 

     # echo $current_item;  
     # fires an error as "Catchable fatal error: Object of class stdClass could not be converted to string" 

     # echo $current_item[1]; 
     # fires an error as "Cannot use object of type stdClass as array in..." 

     # echo array_values($current_item); 
     # fires an error as "array_values() expects parameter 1 to be array, object given in .." 

     # echo $current_item['Tables_in_database-name-here']; 
     #fires an error as "Cannot use object of type stdClass as array in " 

     how do you get that darn thing? :) 

    endforeach; 

回答

1

你的主要問題是屬性名稱Tables_in_database-name-here不能經由通常的$obj->propertyName手段來表示。 PHP允許您通過$obj->{'invalid-variable-name-but-ok-as-a-property'}使用字符串屬性名稱。

我只是通過implode()array_map()構建字符串,如

$string = implode(',', array_map(function($result) { 
    return $result->{'Tables_in_database-name-here'}; 
}, $results)); 

演示〜https://eval.in/172247

關於屬性名稱,你也可以投stdclass對象的數組。例如...

$associativeArray = (array) $result; 
// array(1) { ["Tables_in_database-name-here"] => string(14) "wp_commentmeta" } 

$indexedArray = array_values($associativeArray); 
// array(1) { [0] => string(14) "wp_commentmeta" } 
+0

感謝您的代碼..我現在看到的..是有辦法避免在代碼中使用硬編碼「Tables_in_database名,在這裏」 - 由數字指的是它索引或類似的東西?我想避免使用該特定鍵的原因是,這應該是一個庫函數... –

+0

@AverageJoe我已經添加了一些更多的信息給我的答案 – Phil

+0

甜..現在它完全獨立... 謝謝... –