允许$​​ wpdb mysql查询来处理特定的WordPress类别

时间:2017-02-13 13:15:28

标签: php mysql wordpress

我编写了以下mysql查询,该查询允许使用包含特定单词组合的单元格内容填充php数组,同时跳过所有其他单元格:

<?php
     $data = array(
        array( "name" => "SomeName 1", "type" => "A"),
        array( "name" => "SomeName 2", "type" => "A"),
        array( "name" => "SomeName 3", "type" => "A"),
        array( "name" => "SomeName 4", "type" => "A"),
        array( "name" => "SomeName 5", "type" => "A"),
        array( "name" => "SomeName 6", "type" => "B"),
        array( "name" => "SomeName 7", "type" => "B"),
        array( "name" => "SomeName 8", "type" => "B"),
        array( "name" => "SomeName 9", "type" => "C"),
        array( "name" => "SomeName 10", "type" => "C")
        );
        $result     = array();
        $typeArr    = array();
        $countArr   = array();
        $ratioArr   = array();

        foreach($data as $t){
           $typeArr[$t['type']][]   = $t;
           $countArr[$t['type']]    = count($typeArr[$t['type']]);
           $ratioArr[$t['type']]        = $countArr[$t['type']]/ count($data);
         }

        arsort($countArr);
        $countArrIndex = array_keys($countArr);
        $maxKeyCount = 0 ;$exceptMaxKey = 1;
        $exceptMaxKeyCount=0;
        for($i = 0; $i<count($data); $i++){
            if($i%2 != 0 ){
                 $result[$i]    =  $typeArr[$countArrIndex[$exceptMaxKey]][$exceptMaxKeyCount];
                 if($exceptMaxKey == (count($typeArr)-1)){
                     $exceptMaxKey  = 1;
                     $exceptMaxKeyCount++;
                 }else{
                     $exceptMaxKey++;
                 }

           }else{
               $result[$i]  =  $typeArr[$countArrIndex[0]][$maxKeyCount];
              $maxKeyCount ++;
           }
           }
        echo "<pre>";
        print_r($result);
        $countArr['total'] = count($data);
        print_r($countArr);
        print_r($ratioArr);

除非我想通过特定的WordPress类别或一组WordPress类别来限制其义务,否则它会成功履行其承诺。

此时我还不知道如何修改我的查询以满足我的需求。

有大量的工作示例仅在特定的WordPress类别上执行mysql查询,但是只要我向它们添加$variable = "value"; $query = $wpdb->get_results(" SELECT post_content FROM wp_posts WHERE post_content REGEXP '>(.*) $variable (.*)<' "); ,它们就立即无法填充数组。

如果REGEXP '>(.*) $variable (.*)<'不会使用mysql的$array = array('s' => $value, 'cat' => ID, 'posts_per_page' => -1);语句,我会真的使用's'或类似的东西,这会在我的情况下产生不可预测的结果。

请帮我修改我的查询。

如果你打算帮助我解决这个问题,我会额外感谢你,如果你发现我的查询中的每一个更改或添加内容都很难找到,那就在你附加的代码附近。获得准备好的结果总是很棒,但我想学习并防止自己每次遇到类似问题时一次又一次地问同样的问题。

1 个答案:

答案 0 :(得分:1)

经过一些研究后,我结束了这个有效的解决方案:

$variable = "value";
$query = $wpdb->get_results("
    SELECT ID, post_content
    FROM $wpdb->posts p
        JOIN $wpdb->term_relationships tr ON (p.ID = tr.object_id)
        JOIN $wpdb->term_taxonomy tt ON (tr.term_taxonomy_id = tt.term_taxonomy_id)
        JOIN $wpdb->terms t ON (tt.term_id = t.term_id)
        WHERE post_content REGEXP '>(.*) $variable (.*)<'
        AND tt.taxonomy = 'category'
        AND t.term_id = '###'
");

查询的最后一行是我应该用所需的WordPress类别ID号替换###的地方。