2017-04-21 58 views
0

在下面的函数get_brand()我想在第一行添加文本: - 选择 - 。 我的想法是使用array_merge。但是我会在所有选项上获得一个空行。添加默认 - 选择 - 选项结果数组在wordpress

我需要做些什么来获取文本: - 选择顶部?

function get_brand() { 
global $wpdb; 

    $brand_array = $GLOBALS['wpdb']->get_results("SELECT brand FROM " . $wpdb->prefix . "automatten GROUP BY brand ORDER BY brand ASC"); 
    $select = array("brand" => '--Select--'); 
    $result = array_merge($select, $brand_array); 
return $result; 
} 

结果是:

阵列([品牌] => - 选择 - [0] => stdClass的对象([品牌] => AIXAM)[1] => stdClass的对象([品牌] =>阿尔法)[2] => stdClass的 对象([品牌] => AMC)[3] => stdClass的对象([品牌] => Artega)

+0

看到结果列表。它被填满,所以不是空的 – Hermants

+1

来自数据库的值是对象,而不是数组。尝试使'$ select'成为一个包含'stdClass'对象的数组,其中'brand'属性的值为'--Select - '。 – StuBez

+0

你能分享你的预期产出吗? –

回答

1

你的结果是在stdClass格式,因此请使您的结果与对象相同,创建该类的数组,然后使用array_merge li柯,

$brand_array = $GLOBALS['wpdb']->get_results("SELECT brand FROM " . $wpdb->prefix . "automatten GROUP BY brand ORDER BY brand ASC"); 
$brand = new stdClass; // create a new object here 
$brand->brand = '--Select--'; // assign Select here 
$result = array_merge(array($brand), $brand_array); // now use array merge 
+0

正确的解决方案!谢谢。 – Hermants

+0

太棒了,请打上勾号,以便其他用户可以从此答案中获得帮助。 –

0

在这里,我们type-castingarrayobject

更改为:

array_merge($select, $brand_array); 

此:

array_merge((object)$select, $brand_array); 

PHP代码:

<?php 
$select = array("brand" => '--Select--'); 

function get_brand() 
{ 
    global $wpdb; 

    $brand_array = $GLOBALS['wpdb']->get_results("SELECT brand FROM " . $wpdb->prefix . "automatten GROUP BY brand ORDER BY brand ASC"); 
    $select = array("brand" => '--Select--'); 
    $result = array_merge((object)$select, $brand_array); 
    return $result; 
}