【问题标题】:Array value to string in PHPPHP中将数组值转换为字符串
【发布时间】:2019-02-24 09:45:36
【问题描述】:

我有一些从数据库中随机获取数据的代码,但是每当我在浏览器中打印数据时,看起来都是这样的 - ["data"]。我希望它是一个清晰的字符串。我怎样才能做到这一点?谢谢!

代码如下:

<?php 
   require '../wordbeater/adminpanel/includes/dbh.inc.php'; 

   $result=mysqli_query($con, "SELECT * FROM users ORDER BY RAND() LIMIT 6");

   $count = 0;
   while($row=mysqli_fetch_row($result)){
       $postsarray["one.$count."] = $row[1];
       $postsarray["two.$count."] = $row[2];
       $count++;
   }

   $encodedArray = array_map(utf8_encode, $postsarray);
   echo $encodedArray;


   mysqli_close($con);

   ?>

【问题讨论】:

  • 告诉我们你得到了什么和你期望什么
  • 使用implode,而不是array_map
  • 你不能在数组上使用echo - 使用var_dump($encodedArray);
  • 重要问题:您的数据是否以 ISO 8859-1 / Windows 1252 编码存储?因为这是 utf8_encode 假设的,如果不是,它会破坏你的文本。由于名称选择不当,许多人错误地(或只是不必要地)使用它。
  • array_map(utf8_encode, $postsarray) - 您确定该行不会产生错误消息吗?常量utf8_encode 定义在哪里?

标签: php arrays string


【解决方案1】:

尝试使用:

   $result=mysqli_query($con, "SELECT * FROM users ORDER BY RAND() LIMIT 6");

   $count = 0;

   while ($row = $result->fetch_row()) {
         $postsarray["one.$count."] = $row[1];
         $postsarray["two.$count."] = $row[2];
         $count++;
    }

【讨论】:

  • 请对该代码添加一些解释,以便其他人可以从中学习
【解决方案2】:

我认为您应该选择mysqli_fetch_assoc,因为它会为您提供与数据库相同的关联数组。 例如

while($row=mysqli_fetch_assoc($result)){
   $postsarray["one.$count."] = $row["column_name_u_want_to_fetch"];
   $postsarray["two.$count."] = $row["2_column_name_u_want_to_fetch"];
   $count++;
}

【讨论】:

    【解决方案3】:

    您可以直接将其存储在变量中,以便将其作为字符串。 例如

    $stringone="";
    $stringtwo="";
    while($row=mysqli_fetch_assoc($result)){
    $stringone.$count = $row["column_name_u_want_to_fetch"];
    $stringtwo.$count = $row["2_column_name_u_want_to_fetch"];
    $count++;
    
    }
    
    for($i=0; $i<mysqli_num_rows($result); $i++)
    {
    
    echo $stringone.$i;
    echo $stringtwo.$i;
    }
    

    【讨论】:

    • 现在我得到了 00 作为输出。
    • $stringone.$count - 那应该怎么做?这对我来说看起来很不对
    【解决方案4】:

    删除“ORDER BY RAND() LIMIT 6”试试

    【讨论】:

    • 请对该代码添加一些解释,以便其他人可以从中学习
    猜你喜欢
    • 2011-01-17
    • 1970-01-01
    • 1970-01-01
    • 2018-01-29
    • 2013-08-12
    • 2021-12-27
    • 1970-01-01
    • 2010-10-15
    相关资源
    最近更新 更多