2016-11-15 98 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