doushang2571 2013-01-30 16:42
浏览 32
已采纳

将变量存储在数组中 - PHP

I have some PHP on my site which contains the following portion of code:

'choices' => array ('london' => 'London','paris' => 'Paris',),

Currently this list is static - I manually add to it however I want to generate the list dynamically.

I'm using the following code to create an array dynamically from WordPress & store in a variable:

function locations() {
   query_posts(array('orderby' => 'date', 'order' => 'DESC' , 'post_type' => 'location'));
   if (have_posts()) :
      while (have_posts()) : the_post();
        $locations = "'\'get_the_slug()'\' => '\'get_the_title()'\',";
      endwhile;
   endif;
   wp_reset_query();
   $locations_list = "array (".$locations."),";
   return $locations_list; // final variable
}

Now, this is where I'm stuck :-)

How do I now assign $locations_list to 'choices'?

I tried 'choices' => $locations_list but it crashed my site.

Many thanks for any pointers.

  • 写回答

3条回答 默认 最新

  • dougu6815 2013-01-30 16:45
    关注

    Erm... whut?

    $locations_list = array();
    query_posts(...);
    while(have_posts()) {
      the_post();
      $locations_list[get_the_slug()] = get_the_title();
    }
    wp_reset_query();
    return $locations_list;
    

    I don't know where you read that you could build variables from a string, but... you can't (except eval) so just read the array docs and go from there.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?