获取数组到字符串转换错误

时间:2016-10-11 04:37:00

标签: php arrays

有人可以帮我解决这段代码的问题吗?我试图将获取的数据存储到数组,我想基于该数组的值。我收到Array to string conversion的错误。数组的数据类型值为string

这是代码。

            $sql3 ="SELECT DISTINCT subj_descr FROM subj_enrolled WHERE enroll_ref = '$ref'";
           $results = mysqli_query($con, $sql3);
           $data = array();
              while($row = mysqli_fetch_array($results)){
                      $data[] = array($row['subj_descr']);
              }


            $sql ="SELECT * FROM notification WHERE subj_descr IN ({implode(',', $data})";
           $result = mysqli_query($con, $sql);

           $count = mysqli_num_rows($result);

4 个答案:

答案 0 :(得分:0)

删除while循环中的array

$sql3 ="SELECT DISTINCT subj_descr FROM subj_enrolled WHERE enroll_ref = '$ref'";
       $results = mysqli_query($con, $sql3);
       $data = array();
          while($row = mysqli_fetch_array($results)){
                  $data[] = $row['subj_descr'];
          }


        $sql ="SELECT * FROM notification WHERE subj_descr IN ({implode(',', $data})";
       $result = mysqli_query($con, $sql);

       $count = mysqli_num_rows($result);

答案 1 :(得分:0)

您正在创建multidimensional数组,因此请更改此声明

$data[] = array($row['subj_descr']);

$data[] = $row['subj_descr'];

由于SQL IN语句总是使用单维数组,因此也要在query where子句中进行更改。

我已全部更改,请尝试以下代码:

 <?php
    $sql3 ="SELECT DISTINCT subj_descr FROM subj_enrolled WHERE enroll_ref = '$ref'";
    $results = mysqli_query($con, $sql3);
    $data = array();
    while($row = mysqli_fetch_array($results)){
        $data[] = $row['subj_descr'];
    }
    $dataStr = implode(',', $data);

    $sql ="SELECT * FROM notification WHERE subj_descr IN (".$dataStr.")";
    $result = mysqli_query($con, $sql);

    $count = mysqli_num_rows($result);
    ?>

答案 2 :(得分:0)

创建一个新变量并在其中内爆。

试试这个

$implodeAray = implode(",", $data);
$sql ="SELECT * FROM notification WHERE subj_descr IN ($implodeAray)";

答案 3 :(得分:0)

在循环时将数组元素存储在另一个数组中。

这样做:

$sql3 ='SELECT DISTINCT subj_descr 
        FROM subj_enrolled 
        WHERE enroll_ref = "$ref"';

$results = mysqli_query($con, $sql3);
$data = array();

while($row = mysqli_fetch_array($results)){
    //Your error was here
    //Each elements is escaped for security reasons
    $data[] = mysqli_escape_string($con,$row['subj_descr']);          
}

//This implodes and puts a single quote around each element
$dataIn= '\'' . implode( '\', \'', $data ) . '\'';

$sql ="SELECT * FROM notification 
       WHERE subj_descr IN ($dataIn)";

$result = mysqli_query($con, $sql);

$count = mysqli_num_rows($result);