如何将2个变量添加到数组中?

时间:2013-11-27 10:06:13

标签: php arrays wordpress

我有以下代码:

这里我声明了获取类别名称和slug

的代码
    $args = array(
            'orderby' => 'name',
            'order' => 'ASC',
            'hide_empty' => 0,
        'taxonomy'           => 'category'
        );
        $categories = get_categories($args);
        $categories_name = array(); // here i get the category name
    $categories_ids = array(); // here i get the category slug
    foreach($categories as $category){
          $categories_name[] = $category->name;
      $categories_ids[] = $category->slug;
        }

以下是在我的后端回显的设置,其中包含要选择的用户的类别名称

    $this->settings['categoriesmain3'] = array(
          'section' => 'general',
          'title'   => __( 'Select Right Block Category' ),
          'desc'    => __( 'Here you can select the main category for main right block.' ),
          'type'    => 'select',
          'std'     => '',
          'choices' =>  array('$categories_name' => '$categories_ids') //I am trying to do 
        );
    $settings = get_option('mytheme_options');
    $my_choices_cat3  = $settings['categoriesmain3'];

我正在尝试添加choices =>代码array('$categories_name' => '$categories_ids')',但它不能像那样工作。在我手动添加选择字段的示例中,我有'choices' => array('Choice 1' => 'choice1', 'Choice 2' => 'Choice 2'),那么我想要添加动态列表的choices元素的正确语法是什么?

1 个答案:

答案 0 :(得分:2)

这可以通过创建一个数组来解决,使用类别名称作为键,类别ID作为值。

$categories = get_categories($args);
$categories_options = array();

foreach($categories as $category){
  $categories_options[$category->name] = $category->slug;
}

然后,您可以使用以下行添加列表。

'choices' => $categories_options