【问题标题】:Store variable inside array - PHP在数组中存储变量 - PHP
【发布时间】:2013-01-14 13:43:16
【问题描述】:

我的网站上有一些 PHP,其中包含以下代码部分:

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

目前这个列表是静态的 - 我手动添加到它但是我想动态生成列表

我正在使用以下代码从 WordPress 动态创建数组并存储在变量中:

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
}

现在,这就是我卡住的地方:-)

我现在如何将$locations_list 分配给'choices'

我尝试了'choices' => $locations_list,但它使我的网站崩溃了。

非常感谢您的任何指点。

【问题讨论】:

  • var_dump 的输出是什么$locations_list
  • 我现在就试试 :-)
  • 是的,并在问题中更新并在此处回复。 :)

标签: php arrays wordpress function variables


【解决方案1】:

呃……什么?

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

我不知道您在哪里读到可以从字符串构建变量,但是...您不能(eval 除外)所以只需阅读 array 文档并从那里开始。

【讨论】:

  • 这是一个愚蠢的菜鸟错误。对不起。当我运行该代码时,我的var_dump ($locations_list) = array(0) { }。但是,这种自定义帖子类型肯定有帖子。有什么想法吗?
  • 尝试在循环中输出一些东西,看看它是否在迭代?
  • 我认为,在这种情况下,'choices' 是数组的关联索引;所以他想做的是$array['choices'] => $locations_list; ...但我可能是错的。我想他网站上'choices' => array (...),的代码实际上更像array('choices' => array (...), ... );
  • 会做 - 回到 2 - 感谢您在这里对我的耐心:)
  • 这似乎不对。您的服务器上是否有错误日志文件?
【解决方案2】:

尝试以下操作:-

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

【讨论】:

    【解决方案3】:

    你可以用这个;

    <?php
    function locations() {
        $locations = array();
        query_posts("orderby=date&order=DESC&post_type=location");
        if (have_posts()) {
            while (have_posts()) {
                the_post();
                $locations[] = get_the_slug() ."#". get_the_title();
            }
        }
        wp_reset_query();
        return $locations;
    }
    
    // using
    $locations = locations();
    foreach ($locations as $location) {
        list($slug, $title) =@ explode("#", $location, 2);
        echo $slug, $title;
    }
    ?>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-17
      • 2015-04-21
      • 1970-01-01
      • 1970-01-01
      • 2015-05-31
      • 1970-01-01
      • 1970-01-01
      • 2015-03-11
      相关资源
      最近更新 更多