在数组中打印数组(在WordPress中使用MapPress生成地图)

时间:2012-10-18 23:16:12

标签: php arrays wordpress multidimensional-array

简短版:

我需要制作一个数组:

$locations = array(
    [0] => 'first location',
    [1] => 'second location'
);

对此:

$locations = array( 'first location', 'second location' );

长版

我在WordPress中使用一个名为MapPress的插件来动态生成地图。我需要将一个值数组打印到另一个数组中,以便生成一个映射。 The documentation表示我可以动态执行此操作,但这似乎意味着我可以生成地图,只要我知道需要多少个地图点。我想根据这些自定义帖子中的许多内容生成地图生成。

我从帖子中提取自定义信息以填充字段并将收集的数组存储到另一个数组中。我正在使用这里讨论的方法来提取我需要的每个帖子的信息并将其存储在名为$ locations的数组中。根据文档,我需要将数组打印到没有键值(“[0] =>”)的数组中,但我似乎无法找到如何有效地执行此操作。看起来像是this was a problem that another person had,但是因为她的特殊需求而无法解决这个问题。

用于完成所有这些操作的代码如下所示。

// Let's make a new map.
$mymap = new Mappress_Map(array("width" => 800));

// Run a loop to grab all posts of type "location"
global $post;
$tmp_post = $post;
$args = array( 'post_type' => 'location', 'posts_per_page'=> -1 );
$myposts = get_posts( $args );

$locations = array();
foreach( $myposts as $post ) : setup_postdata($post);

    // Grab all the post's necessary data for creation of the map 
    $title = get_the_title();
    $id = get_the_ID();
    $location_address = get_field("location_address");
    $location_excerpt = get_field("location_excerpt");

    // Plug that data into Mappress' stuff, using dynamic variables
    $mypoi = new Mappress_Poi(array(
        "title" => $title, 
        "body" => $location_excerpt, 
        "address" => $location_address .'<a href="'.$id.'">More Information >></a>'
    ));

    // This converts the address to a longitude/latitude location for the plugin's use
    $mypoi->geocode(); 

    // this is where I get hung up. I need to print the array without the key values
    $locations[] = $mypoi;
endforeach;

$post = $tmp_post; 
// print_r($locations); when I print_r them like they are, they have key values

$mymap->pois = array($locations); //this generates all the maps POIs to create the map
echo $mymap->display(array("directions"=>"none")); // this just displays the map

我知道,啰嗦​​。但这是一个特定的问题,可以通过所有可用信息更容易解决。

谢谢!

修改

$ locations打印了我想要的东西,但是@mario让我意识到它应该按原样接受数组。正如我设置的那样,就是这样:

$locations = array();
$mymap->pois = array($locations);

这意味着打印出来:

$mymap->pois = array( array('location info 1', 'location info 2')); 

我需要做的就是这个;

$mymap->pois = $locations; 

它完美无缺。我觉得很蠢。我需要这个才能最终得到答案。感谢大家的建议!

1 个答案:

答案 0 :(得分:0)

这将根据您的意愿打印任何数组(在本例中为$locations)。 $o包含您应该打印的输出。

$a = $locations;
$o = '$locations = array(';
foreach ($a as &$v)
    $v = "'$v'";
$o .= implode(', ', $a);
$o .= ');';