在wordpress

时间:2017-04-21 11:54:36

标签: php function html-select

在下面的函数get_brand()中我想在第一行添加文本:--Select--。 我的想法是使用array_merge。但是我在所有选项上都有一个空行。

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

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对象([品牌] => Alfa)[2] => stdClass的   对象([品牌] => AMC)[3] => stdClass对象([品牌] => Artega)

2 个答案:

答案 0 :(得分:1)

您的结果是stdClass格式,所以创建一个与您的结果相同的对象,创建该类的数组,然后使用array_merge,

$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

答案 1 :(得分:0)

我们type-casting arrayobject

将其更改为:

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;
}