【问题标题】:How to store database in to array in php [closed]如何在php中将数据库存储到数组中[关闭]
【发布时间】:2016-08-14 02:30:46
【问题描述】:

我需要将列名“thasaurus”中的值存储到数组名“doc[i]”中image

【问题讨论】:

  • 那么问题出在哪里?
  • 请不要在您的代码中使用图片,因为有人想尝试您的代码,这对我们没有用,谢谢
  • $sql = "SELECT id, thasaurus FROM product"; $result = mysqli_query($conn, $sql); $doc= 数组(); $i=1; //if (mysqli_num_rows($result) > 0) { // 输出每一行的数据 while($row = mysqli_fetch_assoc($result)) { //$Str1=mysqli_num_rows($result); $doc[] = $row[ 'thasaurus' ]; //回显 $doc[$i]; $i++; } 回声 $doc[$i];回声“
    ”;
  • 请将$i=0;初始化为$doc[]数组总是从零开始。
  • @Atif 是否使用$i 都没有关系。 $row['thasaurus'] 的值会自动按 0、1、2、3 的顺序插入到$doc 中,无论 $i 的值如何

标签: php mysql arrays database store


【解决方案1】:

您可以使用json_encode将数组转换为JSON,以便将其插入DB,在检索时您可以使用json_decode。

【讨论】:

  • 如果您的数组不是关联数组,您还可以使用explode 和implode 将数组转换为字符串,反之亦然。
  • 好消息是MySQL 5.7 supports JSON。我认为你在正确的轨道上。如果你能用一些代码改进你的答案,那在我看来是正确的答案。
【解决方案2】:
$sql1="SELECT id,thasaurus  FROM  `product`";
$res1=mysqli_query($conn,$sql1);
$doc=array();
while($row1=mysqli_fetch_array($res1))
 {
   $doc[]=$row1['thasaurus'];
 }
 var_dump($doc);//to check the values in that variable

如果要回显该变量,请使用 foreach

foreach($doc as $document)
 {
  echo $document."<br>"
 }

或通过 for 循环,您可以提取该值

for($i=0;$i<count($doc);$i++)
{  
  echo $doc[$i];
   echo "<br>";
}

【讨论】:

    【解决方案3】:

    试试这个代码..

    <?php   
    $sql = "SELECT id, thasaurus FROM product"; 
    $result = mysqli_query($conn, $sql); 
    
    $doc= array(); 
    
    if (mysqli_num_rows($result) > 0) 
    {
         // output data of each row
          while($row = mysqli_fetch_assoc($result)) 
          { 
            $doc[] = $row['thasaurus'];
          } 
    }
    echo "<pre>"; print_r($doc);
    ?>
    

    【讨论】:

    • $i 在当前上下文中无关紧要。您正在使用 $i=0 创建一个索引从 0 开始的关联数组。这不是必需的。只需使用$doc[]=$row['thasaurus']; 即可。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-05
    • 2014-09-17
    • 2021-12-15
    • 2019-02-21
    • 2022-06-15
    • 2016-03-23
    • 2013-08-14
    相关资源
    最近更新 更多