Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/271.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何将mysql数组转换为php数组_Php_Mysql_Arrays - Fatal编程技术网

如何将mysql数组转换为php数组

如何将mysql数组转换为php数组,php,mysql,arrays,Php,Mysql,Arrays,我想做的是将var$title转换为 你应该使用 试试这个 $cg= $mysqli->query("SELECT * FROM news WHERE id='$postid' and status='1' ORDER BY RAND()"); while($sd= $cg->fetch_assoc()){ $title[]= $sd['title']; } print_r($title); 这是完整的参考资料 $cg= $mysq

我想做的是将var$title转换为

你应该使用

试试这个

$cg= $mysqli->query("SELECT * FROM news WHERE id='$postid' and  status='1' ORDER BY RAND()");
       while($sd= $cg->fetch_assoc()){
       $title[]= $sd['title'];
        }

print_r($title);
这是完整的参考资料

 $cg= $mysqli->query("SELECT * FROM news WHERE id='$postid' and  status='1' ORDER BY RAND()");
           while($sd= $cg->fetch_assoc()){
           $title[]= $sd['title'];
            }
    echo $title[1]['col1'];
    echo $title[3]['col2'];
PHP数组总是以0开头,而不是以1开头。 因此,如果数组长度为3,则键为0 1 2,因此使用rand0,2
例如,rand0,count$tile-1

试试这个,我已经根据我的数据库表查询进行了尝试, 正如你所期望的那样

代码:-


希望这有帮助

$title[]=$sd['title'];对不起,我是php新手。感谢Steven直接编写$cg->fetch_array无需遍历查询结果并存储每一行/字段,因为您可以直接使用fetch_all。正如我在Sarath的回答中所评论的那样,无需遍历查询结果并构建辅助数组,因为您可以使用fetch_allSELECT title FROM获取它。。如果只需要标题。另外,rand1,3忽略第1个结果和第5个、第6个结果等。它也会在少于4个结果时中断。由于顺序已经在SQL中随机化,只需回显第一个结果
$cg = $mysqli->query("SELECT * FROM news WHERE id='$postid' and  status='1' ORDER BY RAND()");
$mytitle = $cg->fetch_all(MYSQLI_ASSOC);
$randnews = rand(1, 3);
echo $mytitle[$randnews]['title'];
$cg= $mysqli->query("SELECT * FROM news WHERE id='$postid' and  status='1' ORDER BY RAND()");
       while($sd= $cg->fetch_assoc()){
       $title[]= $sd['title'];
        }

print_r($title);
 $cg= $mysqli->query("SELECT * FROM news WHERE id='$postid' and  status='1' ORDER BY RAND()");
           while($sd= $cg->fetch_assoc()){
           $title[]= $sd['title'];
            }
    echo $title[1]['col1'];
    echo $title[3]['col2'];
$title = array();
while($sd= $cg->fetch_assoc()){
   $title[] = $sd['title'];
}
your can user print_r($title) to check how the array looks 
it will look like 
Array(
  0 =>'first title',
  1 =>'second title',
  2 =>'third title'
)
<?php
     require_once("connect.php");
     $sql=("SELECT * FROM news WHERE id='$postid' and status='1' ORDER BY RAND()");
     $result = $con->query($sql); 
     while($row = $result->fetch_assoc()){
      $array[] = $row['title'];      
      }
     echo "After Sorting".'<pre>';
     print_r($array);
     echo '</pre>';     
?>
[xyz] => "test"
[abc] => "tester"
[pqr] => "user"
[res] => "test"