MySql查询或合并数组为1

时间:2016-07-08 08:51:27

标签: php mysql arrays wordpress

我正在使用ACF Pro,在数据库wp_postmeta中我有2 meta_keydich_vu_%_name_servicedich_vu_%_price_service。两者都有价值,所以如何查询并将其作为(dich_vu_%_name_service,dich_vu_%_price_service)返回。或者,如果MySQL无法处理它,那么如何将这些查询的2个数组合并为一个这样的?

array(objects(['name_service'] => Test,['price_service'] => 9999))

这是我试过的代码

function getAllFaqs() {
global $wpdb;
    $results = $wpdb->get_results( $wpdb->prepare( 
    "SELECT DISTINCT meta_value FROM {$wpdb->prefix}posts,{$wpdb->prefix}postmeta WHERE meta_key LIKE %s AND post_name = %s",
    'dich_vu_%_name_service',
    'bang-gia-dich-vu'
));
    $results2 = $wpdb->get_results( $wpdb->prepare( 
    "SELECT DISTINCT meta_value FROM {$wpdb->prefix}posts,{$wpdb->prefix}postmeta WHERE meta_key LIKE %s AND post_name = %s",
    'dich_vu_%_price_service',
    'bang-gia-dich-vu'
));

    $array = array();
    foreach ($results as $result) {
        $array[]['name_service'] = $result->meta_value;
    }
    $array = $array;
    $array2 = array();
    foreach ($results2 as $result2) {
        $array2[]['price_service'] = $result2->meta_value;
    }
    $array2 = $array2;
    $array3 = array_combine($array,$array2);

感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

联盟是您的朋友,您可以合并这两个查询(请记住,两个结果集必须具有相同数量的列和相同的类型并按顺序排列):

Create

检查docs

P.S:我不知道wordpress但看到prepare返回已清理的查询字符串,因此中间的UNION应该可以工作

答案 1 :(得分:0)

为什么你要把它变得那么复杂。只需像WordPress标准一样使用

global $wpdb;
// Instead of passing post slug, you need to use post id here
$myvals1 = get_post_meta($post->ID,"dich_vu_%_name_service", true);
$myvals2 = get_post_meta($post->ID,"dich_vu_%_price_service", true);

$obj = new StdClass();
$obj->name_service = $myvals1;  
$obj->price_service = $myvals2;  

$res = array($obj);

// result 
array(1) {
  [0]=>
  object(stdClass)#245 (2) {
    ["name_service"]=>
    string(4) "Test"
    ["price_service"]=>
    string(4) "9999"
  }
}