2012-08-22 205 views
0

我目前正在研究Wordpress主題中的修改搜索,該主題查詢自定義分類標準location並將其術語顯示爲搜索結果。我無法找到一個內置在WordPress的功能,以處理這個問題,所以我用一個$wpdb query比較兩個stdClass對象

$keywords = $_GET['s']; 
$results = $wpdb->get_results("SELECT * FROM $wpdb->terms WHERE name LIKE '%%$keywords%%'"); 

<ul> 
<?php foreach ($results as $result) :?> 
    <li><?php echo $result->name;?></li> 
<?php endforeach;?> 
</ul> 

的問題與此是表wp_terms不僅存儲自定義分類方面,但其他默認條款以及。因此,爲了顯示搜索結果只是爲自定義分類,而不是其他默認的條款,我想用get_terms獲得基於關閉的get_terms結果與in_array都屬於自定義分類從表wp_termslocation和顯示方面的條款的

$keywords = $_GET['s']; 
$results = $wpdb->get_results("SELECT * FROM $wpdb->terms WHERE name LIKE '%%$keywords%%'"); 

$terms = get_terms("location"); 

<ul> 
<?php foreach ($results as $result) :?> 
    if(in_array($result->name, $terms)) :?> 
    <li><?php echo $result->name;?></li> 
    <?php endif;?> 
<?php endforeach;?> 
</ul> 

然而,$results$terms都是stdClass的對象,所以in_array不起作用。

是否有一個函數,方法或MySQL查詢,這將允許我顯示對象$results的結果基於對象的內容$terms

在此先感謝。

編輯: 內容的$terms

Array ( 
    [0] => stdClass Object ([term_id] => 32 [name] => US [slug] => us [term_group] => 0 [term_taxonomy_id] => 32 [taxonomy] => signs [description] => [parent] => 25 [count] => 1) 
    [1] => stdClass Object ([term_id] => 22 [name] => EU [slug] => eu [term_group] => 0 [term_taxonomy_id] => 22 [taxonomy] => signs [description] => [parent] => 0 [count] => 3) 
    [2] => stdClass Object ([term_id] => 26 [name] => AU [slug] => au [term_group] => 0 [term_taxonomy_id] => 26 [taxonomy] => signs [description] => [parent] => 22 [count] => 1) 
    [3] => stdClass Object ([term_id] => 27 [name] => IE [slug] => ie [term_group] => 0 [term_taxonomy_id] => 27 [taxonomy] => signs [description] => [parent] => 22 [count] => 2) 
    [4] => stdClass Object ([term_id] => 23 [name] => PK [slug] => pk [term_group] => 0 [term_taxonomy_id] => 23 [taxonomy] => signs [description] => [parent] => 0 [count] => 2) 
) 

回答

0

你可以將它們轉換成陣列,

(array) $variable; 

或者,如果您stdClass已經包含嵌套stdClasses,你可以做到以下幾點:

function obj_to_array_recursive(stdClass $obj) { 
    foreach ($obj as &$element) { 
     if ($element instanceof stdClass) { 
      obj_to_array_recursive($element); 
      $element = (array)$element; 
     } 
    } 
    $obj = (array)$obj; 
    return $obj; 
} 
+0

感謝您的喲你的幫助,我用'obj_to_array_recursive($ terms)'調用函數;'得到'致命錯誤:調用未定義的函數obj_to_array_recursive()'。不知道如果我正確地調用它,有什麼建議嗎? – dcd0181

+0

@ dcd018:您在使用它之前是否定義了該功能?這不是一個PHP本地函數,它是我寫的函數... –