【问题标题】:Converting an array into a string in PHP在 PHP 中将数组转换为字符串
【发布时间】:2023-03-09 02:40:02
【问题描述】:

我已经被这个问题困扰了一段时间了。我确信有一个简单的解决方案,但我仍然围绕着 php。

我想从数据库中获取一些数据并将其保存到另一个数据库中。

使用 SQL,我设法获取该数据并将其保存在一个数组中。现在我想将该数据转换为字符串以保存到不同的数组中(如果有一种方法可以直接执行此操作而无需先保存到数组中,那么我全神贯注)。

我以这种格式获取数据。

Array ( [0] => Array ( [0] => 414208 [InterestedEntityId] => 414208 [1] => 126.61370996251785 [Score] => 126.61370996251785 ) [1] => Array ( [0] => 479516 [InterestedEntityId] => 479516 [1] => 73.531040944194 [Score] => 73.531040944194 ) [2] => Array ( [0] => 4129769 [InterestedEntityId] => 4129769 [1] => 54.390965049372674 [Score] => 54.390965049372674 )

我想把它转换成:

414208  126.61370996251785
479516  73.531040944194  
4129769 54.390965049372674

这是我的代码:

$sql = mysql_query("SELECT Id, Score FROM users.`table1` WHERE UserId= $userID", $dbh1);

$table = array();

while ($row = mysql_fetch_array($sql))
    $table[] = $row;

$table = implode($table);


mysql_query("INSERT INTO $tbl_name(table) VALUES ('$table')", $dbh2);

有人可以帮忙吗?

【问题讨论】:

    标签: php mysql sql phpmyadmin


    【解决方案1】:

    一个简单的 foreach 循环就可以完成这项工作。

    做一张漂亮的桌子:

    $output = '<table border="1">';
    foreach($table as $row){
        $output .= '<tr><td>'.$row[0].'</td><td>'.$row[1].'</td></tr>';
    }
    $output .= '</table>';
    echo $output;
    

    纯文本:

    $output = '';
    foreach($table as $row){
        $output .= $row[0].' '.$row[1].'<br>';
    }
    echo $output;
    

    【讨论】:

    • 它应该是 $output .= $row[0]。' '.$row[1] 。 '
      '; (你忘了 . before
      )但除此之外它是完美的。非常感谢!
    【解决方案2】:

    作为您的问题的解决方案,请尝试执行以下代码 sn-p。

     <?php
       try
       {
            $a=array(array(414208,126.61370996251785),array(414208,126.61370996251785));
            $string='';
            foreach($a as $key=>$value)
            {
               if(!is_array($value))
               {
                  throw new Exception('Not an array.');
                }
               else
               {
                $string=join(' ',$value);
               }        
               }
          }
         catch(Exception $e)
        {
       echo $e->getMessage();
        }    
       echo $string;
    
     ?>
    

    【讨论】:

      猜你喜欢
      • 2012-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-29
      • 2013-08-12
      • 2021-12-27
      • 1970-01-01
      相关资源
      最近更新 更多