使用PHP创建具有特定格式的JSON

时间:2015-10-31 16:17:10

标签: php android mysql json

我的服务器数据库中有一个表,其中包含以下列:

|---category--|---name---|---description---|

所以,举个例子说我们在表格中有以下数据:

|---CategoryA--|---name1---|---description1---|
|---categoryB--|---name2---|---description2---|
|---categoryA--|---name3---|---description3---|
|---categoryA--|---name4---|---description4---|

我想创建一个.php文件,当我从我的Android应用程序调用它时,我想获得一个JSON作为响应。 json文件希望具有以下格式:

{
"CategoryA":[
{"name":"name1","description":"description1"},
{"name":"name3","description":"description3"},
{"name":"name4","description":"description4"}
],
"KatigotiaB":[
{"name":"name2","description":"description2"}
]
}

我创建了一个.php文件,它以JSON格式返回数据,但不是我想要的特定格式。这是我的.php文件:

<?php
    header('content-type: text/html; charset=utf-8');
    try {
        $pdo = new PDO('mysql:host=****;dbname=****', '****', '****', array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    } catch(PDOException $e) {
        echo 'ERROR: ' . $e->getMessage();
    }

    $stmt = $pdo->prepare("SELECT * FROM `db`.`table`;");
    $stmt->execute();

    $results = array();

    while ($obj = $stmt->fetch(PDO::FETCH_ASSOC)) {
        array_push($results, $obj);
    }

    function replace_unicode_escape_sequence($match) {
        return mb_convert_encoding(pack('H*', $match[1]), 'UTF-8', 'UTF-16BE');
    }

    $str = preg_replace_callback('/\\\\u([0-9a-f]{4})/i', 'replace_unicode_escape_sequence', json_encode($results));


    echo $str;
?>

结果是:

[{"category":"CategoryA","name":"name1","description":"description1"},
{"category":"CategoryB","name":"name2","description":"description2"},
{"category":"CategoryA","name":"name3","description":"description3"},
{"category":"CategoryA","name":"name4","description":"description4"}]

由于我是Android开发人员并且我的PHP知识有限,我如何才能重新创建我的.php文件以获得正确的JSON格式?

更新: 这是有效的

 foreach ($nameDescriptionPairs as $nameDescriptionPair) {
            $result[$row['category']][] = array(
                'name'          => $nameDescriptionPair['name'],
                'description'   => $nameDescriptionPair['description']
            );

        }

2 个答案:

答案 0 :(得分:0)

一个主要问题是您将内容类型设置为text / html。您不打印HTML,应将其设置为JSON:

header('content-type: application/json; charset=utf-8');

不确定它是否有效,但您的回调是不必要的:

$str = preg_replace_callback('/\\\\u([0-9a-f]{4})/i', 'replace_unicode_escape_sequence', json_encode($results));

如果您真的不希望json_encode转义unicode,请使用此处的JSON_UNESCAPED_UNICODE选项:http://php.net/manual/en/function.json-encode.php

$str = json_encode($results, JSON_UNESCAPED_UNICODE);

除此之外,您还可以使用JSON_PRETTY_PRINT对其进行格式化,但如果知道它是JSON(设置内容是什么),那么解释JSON的应用程序就不应该这么重要。正确输入应该这样做。

答案 1 :(得分:0)

解决方案#1(简单):

<?php
$host = 'localhost';
$database = '******';
$user = '******';
$password = '******';

$result = [];
try {
    $pdo = new PDO(
        "mysql:host=$host; dbname=$database;",
        $user,
        $password,
        [PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"]
    );

    $stmt = $pdo->prepare("SELECT category, name, description FROM `YOUR_TABLE_HERE`");
    $stmt->execute();

    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $result[$row['category']][] = [
            'name'          => $row['name'],
            'description'   => $row['description'],
        ];
    }
} catch (Exception $e) {
    echo 'ERROR: ' . $e->getMessage();
}

header('content-type: application/json; charset=utf-8');
echo json_encode($result);

解决方案#2(令人讨厌):

我的代码的一个注释:我使用十六进制转换来防止引号问题。因此,即使任何列具有任意数量的",代码也能正常工作。

<?php

function hexToStr($hex) {
    $string = '';
    for ($charIter = 0; $charIter < strlen($hex) - 1; $charIter += 2) {
        $string .= chr(hexdec($hex[$charIter] . $hex[$charIter + 1]));
    }
    return $string;
}

//----------------------

$host = 'localhost';
$database = '******';
$user = '******';
$password = '******';

$result = [];    
try {
    $pdo = new PDO(
        "mysql:host=$host; dbname=$database;",
        $user,
        $password,
        [PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"]
    );

        $query = <<<QUERY
    SELECT category, CONCAT('[', GROUP_CONCAT( CONCAT( '{"name":"', hex( name ) , '", "description":"', hex( description ) , '"}' ) ), ']') raw_json
    FROM `YOUR_TABLE_HERE`
    GROUP BY category
QUERY;

    $stmt = $pdo->prepare($query);
    $stmt->execute();

    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $nameDescriptionPairs = json_decode($row['raw_json'], true);
        foreach ($nameDescriptionPairs as $nameDescriptionPair) {
            $result[$row['category']][] = [
                'name'          => hexToStr($nameDescriptionPair['name']),
                'description'   => hexToStr($nameDescriptionPair['description'])
            ];
        }
    }
} catch (Exception $e) {
    echo 'ERROR: ' . $e->getMessage();
}

header('content-type: application/json; charset=utf-8');
echo json_encode($result);