print_r输出为仅返回最后一项的字符串

时间:2014-09-23 15:09:11

标签: php arrays string wordpress

我使用查询为wordpress网站的所有用户提取geo_latitude和geo_longitude。我需要将所有这些作为变量输出,以便将其插入到映射插件中。

我设法将下面的代码放在一起,并且它与print_r一起使用效果很好,它在屏幕上显示了100多个用户的完整列表。但是,当我尝试将其作为变量输出时,它只返回最终用户的详细信息。

我认为它与foreach有关,但我无法理解如何修复它。

$blogusers = get_users_of_blog();
if ($blogusers) {
$excluded_users = array(1, 10, 11);
foreach ($blogusers as $bloguser) {
if (!in_array($bloguser->user_id, $excluded_users))
{
$user = get_userdata($bloguser->user_id, $excluded_users);

 $user_lat = get_the_author_meta('geo_latitude', $bloguser-> ID);
 $user_long = get_the_author_meta('geo_longitude', $bloguser->ID );

 $gLocations = ($user_lat .',' .$user_long. ' | ' );
 }

$var_users = print_r($gLocations, true);
print_r($gLocations);
 }} 

2 个答案:

答案 0 :(得分:3)

问题在于你正在为循环中的变量初始化一个值,以便在循环退出时只存储最后一个值。你应该使用数组

使用此

$blogusers = get_users_of_blog();
$gLocations =array();
if ($blogusers) {
$excluded_users = array(1, 10, 11);
foreach ($blogusers as $bloguser) {
if (!in_array($bloguser->user_id, $excluded_users))
{

$user = get_userdata($bloguser->user_id, $excluded_users);

 $user_lat = get_the_author_meta('geo_latitude', $bloguser-> ID);
 $user_long = get_the_author_meta('geo_longitude', $bloguser->ID );
 array_push($gLocations, $user_lat .',' .$user_long. ' | ');
 }

$var_users = print_r($gLocations, true);
print_r($gLocations);
 }} 

修改

您可以通过两种方法

来完成此操作
  1. 循环

     foreach($gLocations as $key=>$value){
         echo $value;//'62.7594129,15.425879000000009 |.... so on' will be output
      }// you can also use for loop
    
  2. 正常方法 你可以按索引

    访问数组元素
         echo $gLocations[0]; // '62.7594129,15.425879000000009 |' will be output but only one value will be shown
    

答案 1 :(得分:-1)

你必须做这样的事情:

foreach($gLocations AS $key=>$value) {
  echo $key . " -> " . $value;
}

如果您只想查看值,则可以执行以下操作:

foreach($gLocations AS $value) {
  echo $value . "<br />";
}
编辑:我看到添加到变量$ gLocations也是错误的。这是对您的代码的修复:

$blogusers = get_users_of_blog();
if ($blogusers) {
$gLocations = array();
$excluded_users = array(1, 10, 11);
foreach ($blogusers as $bloguser) {
if (!in_array($bloguser->user_id, $excluded_users))
{
$user = get_userdata($bloguser->user_id, $excluded_users);

 $user_lat = get_the_author_meta('geo_latitude', $bloguser-> ID);
 $user_long = get_the_author_meta('geo_longitude', $bloguser->ID );

 $gLocations[] = ($user_lat .',' .$user_long. ' | ' );
 }
 }

$var_users = print_r($gLocations, true);
print_r($gLocations);
 } 
 foreach($gLocations AS $value) {
  echo $value . "<br />";
}