2016-11-15 96 views
0

在我的脚本中,我从数据库中获取数据并将其存储在数组中并将其输出到json中。一切都是正确的,只是我得到的第一个数组是空的,然后第二个数组有正确的数据。我不明白为什么我会得到第一个空数组。获得null数组,然后得到实际结果在php

我的问题可以解决,如果我得到正确的结果数组没有null数组。 这里是我得到的输出

[[],{"url":"example.com\/sign_pdf\/PDFSign.pdf","name":"PDFSign.pdf","signer":"aman","sequence":"1","message":"Hello","flag":"0"}] 

我不需要第一个空数组。为什么我会这样做。

这是代码。

if(($_GET['action'])&&($_GET['username'])&&($_GET['key'])) { 
    $select = $_GET['action']; 
    $username =$_GET['username']; //no default 
    $key= $_GET['key']; 

    if($key=='abcxyz'){ 
     if($select=='select'){ 
      /* connect to the db */ 
      $connect = mysqli_connect('localhost','root','')or die("Couldn't connect to database!"); 
      mysqli_select_db($connect,'sign') or die ("Couldn't find database");   

      $query ="SELECT * FROM path WHERE signer ='$username' "; 

      $result = mysqli_query($connect,$query); 
      $numrows=mysqli_num_rows($result); 
      $posts[] = array(); 

      if($numrows!==0) { 

       while($row = mysqli_fetch_array($result)) { 
        $post['url'] = $row['url']; 
        $post['name'] = $row['name']; 
        $post['signer'] = $row['signer']; 
        $post['sequence'] = $row['sequence']; 
        $post['message'] = $row['message']; 
        $post['flag'] = $row['flag']; 
        array_push($posts, $post); 
       } 

       header('Content-type: application/json'); 
       echo json_encode($posts); 

      } 
     } 
    } 
} 
+0

而不是$ posts [] = array();使用$ posts = array(); –

回答

1

你被$posts[] = array();

创建array(array())替换此:

$posts[] = array(); 

$posts = array(); 

$posts = array();将创建一个空array(),而不是array(array())

1

$posts[]=array()应该像$posts=array()并采用$posts[]=$post追加$post$posts

$posts = array(); 
if ($numrows !== 0) { 
    while ($row = mysqli_fetch_array($result)) { 
     $post = array(); 
     $post['url'] = $row['url']; 
     $post['name'] = $row['name']; 
     $post['signer'] = $row['signer']; 
     $post['sequence'] = $row['sequence']; 
     $post['message'] = $row['message']; 
     $post['flag'] = $row['flag']; 
     $posts[] = $post; 
    } 
} 
0

您应该删除$ posts数组。 array_push($ posts,$ post)基本上将空的$ posts数组添加到$ post数组中。

1

而不是

$posts[] = array(); 

其中分配一个数组的$posts的第一要素,使用

$posts = array(); 

其中初始化变量,我认为你正在尝试做的。

+0

或者,因为不需要,请保留该行。 – Xorifelse