2014-04-23 174 views
0

我是PHP新手。我正在嘗試格式化JSON。下面是相關的代碼:php webservices中格式化json格式

$query = mysql_query("SELECT * 
FROM `micards` m 
JOIN user u ON m.`mobile` = u.phone"); 

while ($row = mysql_fetch_assoc($query)) { 
    $response["success"] = 1; 
    $name = array('name'=>$row["name"],'email'=>$row["email"],'mobile'=>$row["mobile"]); 
    $phone[] = array('phone'=>$row["phone"],array('card'=>$name)); 
    $response["contacts"] = $phone; 
} 
echo json_encode($response); 

我得到這樣的輸出:

{ 
    "success": 1, 
    "contacts": [{ 
     "phone": "919898989898", 
     "0": { 
     "card": { 
      "name": "abcd", 
      "email": "[email protected]", 
      "mobile": "919898989898" 
     } 
     } 
    }, { 
     "phone": "919898989898", 
     "0": { 
     "card": { 
      "name": "abcd", 
      "email": "[email protected]", 
      "mobile": "919898989898" 
     } 
     } 
    }, { 
     "phone": "8686868686", 
     "0": { 
     "card": { 
      "name": "pan", 
      "email": "[email protected]", 
      "mobile": "8686868686" 
     } 
     } 
    }, { 
     "phone": "8686868686", 
     "0": { 
     "card": { 
      "name": "monk", 
      "email": "[email protected]", 
      "mobile": "8686868686" 
     } 
     } 
    }] 
} 

但我希望它是:

{ 
    "success": 1, 
    "contacts": [{ 
     "phone": "919898989898", 
     { 
      "card": { 
       "name": "abcd", 
       "email": "[email protected]", 
       "mobile": "919898989898" 
      } 
     }, 
     { 
      "card": { 
       "name": "abcd", 
       "email": "[email protected]", 
       "mobile": "919898989898" 
      } 
     } 
    }], 
    [{ 
     "phone": "8686868686", 
     { 
      "card": { 
       "name": "panky", 
       "email": "[email protected]", 
       "mobile": "8686868686" 
      } 
     }, 
     { 
      "card": { 
       "name": "panky", 
       "email": "[email protected]", 
       "mobile": "8686868686" 
      } 
     } 
    }] 
} 

我能做些什麼來得到上面的輸出?

回答

0

只是改變這一部分:

$phone[] = array('phone'=>$row["phone"],array('card'=>$name));  
$response["contacts"] = $phone; 

$response["contacts"][] = array('phone'=>$row["phone"],array('card'=>$name)); 
0

只需複製並粘貼此代碼

while ($row = mysql_fetch_assoc($query)) { 
    $response["success"] = 1; 
    $name = array('name'=>$row["name"],'email'=>$row["email"],'mobile'=>$row["mobile"]); 
    $response["contacts"][] = array('phone'=>$row["phone"],array('card'=>$name)); 
} 
0

請更改

$phone[] = array('phone'=>$row["phone"],array('card'=>$name)) to 
$phone[] = array('phone'=>$row["phone"],'card'=>$name) 
; 
+0

感謝大家的支持。但它不支持以上解決方案 – user3395570

0

我的猜測是關聯數組和您打包的方式存在問題。你可以嘗試像這樣組織你的響應陣列:

$response = [ 
    'success'=>1, 
    'contacts'=>[ 
     'phone'=>$row['phone'], 
     'card'=>[ 
      'name'=>$row['name'], 
      'email'=>$row['email'], 
      'mobile'=>$row['mobile'] 
     ] 
    ] 
]; 

它應該工作,沒有檢查出來你。

+0

是PHP嗎?沒有。 – Jerry

+0

是的,它的PHP,對於非常慢的反應抱歉... –