【问题标题】:php function add foreach array on another array to populate a select drop downphp 函数在另一个数组上添加 foreach 数组以填充选择下拉列表
【发布时间】:2013-09-28 09:45:20
【问题描述】:

我启动了这个 PHP 函数。此功能是在 WordPress 中填充下拉选择菜单。

acf/load_field 钩子可以帮助我轻松地将其钩入。请参阅此处的文档。 http://www.advancedcustomfields.com/resources/filters/acfload_field/

这是我的函数,它使用get_posts 来查询我的circuit post_type。这一点工作正常。

见下文...

function my_circuit_field( $field )
{
    $circuits = get_posts(array(
        "post_type" => "circuit",
        "post_status" => "publish",
        "orderby" => "menu_order",
        "order" => "ASC",
        "posts_per_page"  => -1
    ));
    $field['choices'] = array();
    $field['choices'] = array(
        0 => 'Select a circuit...'
    );
    foreach($circuits as $circuit){
        $field['choices'] = array(
            $circuit->post_title => $circuit->post_title
        );
    }       
    return $field;
}
add_filter('acf/load_field/name=event_calendar_circuit', 'my_circuit_field');



我遇到的问题是……

$field['choices'] = array(
    0 => 'Select a circuit...'
);

没有加入到这个前面...

foreach($circuits as $circuit){
    $field['choices'] = array(
         $circuit->post_title => $circuit->post_title
    );
}


只有$circuits foreach 显示在我的下拉列表中,我希望“选择电路”作为下拉选择菜单中的第一个选项出现。

谁能帮我理解我哪里出错了?

【问题讨论】:

    标签: php wordpress function


    【解决方案1】:

    当您使用 = 时,它会将当前值替换为 = 符号后面的值。每次分配新值时,您都会替换 $field['choices'] 的整个值。

    你可能想做类似的事情

    foreach($circuits as $circuit){
        $field['choices'][$circuit->post_title] = $circuit->post_title;
    }
    

    顺便说一句,$field['choices'] = array(); 行在您的代码中是无用的,因为您更改了以下行中的值。

    【讨论】:

      【解决方案2】:

      使用这个:

      $field['choices'] = array(
          0 => 'Select a circuit...'
      );
      $arr = array();
      foreach($circuits as $circuit){
          $arr = array(
             $circuit->post_title => $circuit->post_title
          );
          $field['choices'] = array_merge($field['choices'],$arr);
      }
      print_r($field);
      

      输出:

      Array
      (
          [choices] => Array
              (
                  [0] => Select a circuit...
                  //and other fields 
                  //with the 0 index value
                  //same as you are requiring
              )
      )
      

      【讨论】:

      • 也谢谢你,但我使用了下面的答案,效果很好。你的也一样好用。谢谢
      猜你喜欢
      • 1970-01-01
      • 2012-07-23
      • 1970-01-01
      • 1970-01-01
      • 2018-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多