如何使用PHP从MySQL表中检索JSON数据?

时间:2015-03-09 08:17:38

标签: php mysql json

预期的JSON:

{
    id: 1,
    name: "Sony Xperia Z3",
    price: 899,
    specs: {
            manufacturer: "Sony",
            storage: 16,
            os: "Android",
            camera: 15
    },
    description: " WOW",
    rating: 4,
    image: {
            small: "assets/images/sony-xperia-z3.jpg",
            large: "assets/images/sony-xperia-z3-large.jpg"
    }
    }

MySQL表:

CREATE TABLE IF NOT EXISTS `phones` (
  `id` tinyint(4) NOT NULL AUTO_INCREMENT,
  `name` varchar(100) NOT NULL,
  `price` int(11) NOT NULL,
  `manufacturer` varchar(100) NOT NULL,
  `storage` tinyint(4) NOT NULL,
  `os` varchar(100) NOT NULL,
  `camera` tinyint(4) NOT NULL,
  `description` varchar(400) NOT NULL,
  `rating` tinyint(4) NOT NULL,
  `image_small` varchar(200) NOT NULL,
  `image_large` varchar(200) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;`

我的PHP代码:

<?php
    header("Access-Control-Allow-Origin: *");
    header("Content-Type: application/json; charset=UTF-8");    
    $conn = new mysqli("localhost", "root", "", "php_test");    
    $result = $conn->query("SELECT id, name,price,manufacturer,storage,os,camera,description FROM phones");

    $outp = "[";
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
    if ($outp != "[") {$outp .= ",";}

    $outp .= '{"id":"'  . $rs["id"] . '",';
    $outp .= '"name":"' . $rs["name"]   . '",'; 
    $outp .= '"price":"' . $rs["price"]   . '",'; 
    $outp .='"specs:"'.'{"manufacturer":"'. $rs["manufacturer"].'"}'.'",'; 
    $outp .= '"storage":"' . $rs["storage"]   . '",'; 
    $outp .= '"os":"' . $rs["os"]   . '",'; 
    $outp .= '"camera":"' . $rs["camera"]   . '",'; 
    $outp .= '"description":"'. $rs["description"]     . '"}'; 

}
$outp .="]";

$conn->close();
echo($outp); 
//echo json_encode($outp); 
?>

2 个答案:

答案 0 :(得分:1)

这将解决您的问题

<?php   
    $conn = new mysqli("localhost", "root", "", "php_test");    
    $result = $conn->query("SELECT * FROM phones");
    $array_main = array();
    $arr_row = array();
    $arr_images = array();
    $counter = 0;
    while($results = $result->fetch_array(MYSQLI_ASSOC)) {
        $arr_row[$counter] = $results;
        $arr_row[$counter]['specs'] = array();
        $arr_row[$counter]['specs']['manufacturer'] = $arr_row[$counter]['manufacturer'];
        $arr_row[$counter]['specs']['storage'] = $arr_row[$counter]['storage'];
        $arr_row[$counter]['specs']['os'] = $arr_row[$counter]['os'];
        $arr_row[$counter]['specs']['camera'] = $arr_row[$counter]['camera'];
        $arr_row[$counter]['images'] = array();
        $arr_row[$counter]['images']['small'] = $arr_row[$counter]['image_small'];
        $arr_row[$counter]['images']['large'] = $arr_row[$counter]['image_large'];      
        unset($arr_row[$counter]['manufacturer']);
        unset($arr_row[$counter]['storage']);
        unset($arr_row[$counter]['os']);
        unset($arr_row[$counter]['camera']);
        unset($arr_row[$counter]['image_small']);
        unset($arr_row[$counter]['image_large']);
        $array_main[$counter] = $arr_row[$counter];
        $counter++;
    }

$conn->close();
echo(json_encode($array_main));  
?>

代码说明: 主阵列中有两个json数组。所以我创建了两个名为specs,images的数组。然后我将您的数据值添加到这些数组。最后,我从arr_row数组中删除了以前的元素,并添加了创建的两个数组。

答案 1 :(得分:0)

使用json_encode
 当你有一个数组时,只需使用json_encode将数组转换为json。

    $outp = array();
    while($rs = $result->fetch_array(MYSQLI_ASSOC)) {  
        $outp[]['id'] =  $rs['id']; 
        // assign all data you need e.g name, description etc
       $outp[]['specs'] = array('manufacturer' => $res['manufacturer'], 'storage' => $res['storage'], 'os' => $res['os'], 'camera' => $res['camera']);
    }
    $conn->close();
    echo json_encode($outp);