比较两个stdClass对象

时间:2012-08-22 09:40:10

标签: php mysql wordpress search taxonomy

我目前正在Wordpress主题中进行修改后的搜索,该主题会查询自定义分类location并将其显示为搜索结果。我找不到内置的Wordpress函数来处理这个问题,所以我使用了$wpdb query

$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来获取属于自定义分类location的所有字词并显示表中的字词wp_terms基于get_terms

in_array结果$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

但是,$termsin_array都是stdClass对象,因此$results不起作用。

是否有函数,方法或可能的MySQL查询允许我根据对象$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 ) )

的内容
{{1}}

1 个答案:

答案 0 :(得分: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;
}