2015-07-01 50 views
1

我創建了這個php腳本,這樣我就可以從JSON數據庫中獲取數據,就像一個嬰兒web服務一樣。我創造的東西可以在下面看到。替換JSON字段

$category_id = $_GET["CategoryID"]; 
$sub_id = $_GET["RootID"]; 

// Connect to our db (MySQL) 
$link = mysql_connect('localhost','xxxxxxxx','xxxxx') or die('Cannot connect to the DB'); 
mysql_select_db('bridgeapp',$link) or die('Cannot select the DB'); 

// Default charset 
mysql_query("SET character_set_results = 'utf8', character_set_client = 'utf8', character_set_connection = 'utf8', character_set_database = 'utf8', character_set_server = 'utf8'", $link); 

// Show all subcategories based on $category_id value 
if (isset($category_id)) { 
    $query = "SELECT id, name FROM vrfmp_jbusinessdirectory_categories WHERE parent_id = '".$category_id. "'"; 
    $result = mysql_query($query,$link) or die('Errant query: '.$query); 

} 

// What happens if CategoryID is empty ? (Show Parental Categories) 
if (empty($category_id)) { 
    $query = "SELECT id, name FROM vrfmp_jbusinessdirectory_categories WHERE level = 1"; 
    $result = mysql_query($query,$link) or die('Errant query: '.$query); 

} 


// Fetch data from the db 
$rows = array(); 
while($r = mysql_fetch_assoc($result)) { 
    $rows[] = $r; 
// $rows = str_replace("name", "title", "$rows"); 
} 

// Echo $rows in JSON format 
echo json_encode($rows); 

//Disconnect from our db 
@mysql_close($link); 

運行這個返回我想要的。

When Category ID is empty

When Category ID has a value

我想這樣做是在JSON對象以「標題」,以取代「名稱」字段。任何關於如何用PHP做到這一點的幫助?

預先感謝您。列

+1

'$行[ '標題'] = $行[ '名稱'];未設置($ rows ['name']);' – splash58

回答

1

使用別名

SELECT id, name AS `title` FROM ... 

$rows[] = [ 
    'id' => $r['id'], 
    'title' => $r['name'] 
]; 
+0

偉大而簡單的解決方案。非常感謝你。 –