1

我的数据库(mysql)中有数据,我试图将其拉到 json 格式的页面,以便我可以选择数据以供将来参考。

当前数据输出

{
    "quotes": [
        {
            "season": "3",
            "episode": "2",
            "lines": [
                "Boys:\tSchool day, school day, teacher's golden ru\nKyle:\tAh, damn it! My little brother's trying to follow me to school, again. "
            ]
        },
        {
            "season": "1",
            "episode": "2",
            "lines": [
                "Episode 2 "
            ]
        }
    ]
}

我正在努力的部分是lines这样显示

"lines": [
           {"Boys": "School day, school day, teacher's golden ru"},
           {"Kyle": "Ah, damn it! My little brother's trying to follow me to school, again."}
         ]

我拥有的 PHP

$result = $con->query("SELECT * FROM quotes");
$response = array();
$i=0;
while ($row = $result->fetch_assoc()) { 
    $response[$i]['season']= $row['season'];
    $response[$i]['episode']= $row['episode'];
    $response[$i]['lines'] = explode('\n', $row['lines']);
    $data['quotes'][$i] = $response[$i];
    $i=$i+1;
}
$json_string = json_encode($data);

echo $json_string;

如果有人可以提供帮助,那就太好了!

4

3 回答 3

5
explode('\n', $row['lines']);

应该

explode("\n", $row['lines']);

注意双引号。用前反斜杠表示的控制字符必须用双引号括起来。

于 2013-11-12T15:50:42.937 回答
0

代替

$response[$i]['lines'] = explode('\n', $row['lines']);

$lines = explode("\n", $row['lines']);
$indexedLines = array();

foreach( $lines as $thisLine ) {
    $sepIndex    = strpos( $thisLine, ":\t" );
    $lineIndex   = substr( $thisLine, 0, $sepIndex );
    $lineContent = substr( $thisLine, $sepIndex + 2 );
    $indexedLines[ $lineIndex ] = $lineContent;
}
$response[$i]['lines'] = $indexedLines;

对于允许每个扬声器多行并保留行的顺序的模型,请替换:

$indexedLines[ $lineIndex ] = $lineContent;

类似于以下内容:

$indexedLines[] = array( 'speaker' => $lineIndex, 'line' => $lineContent );
于 2013-11-12T16:07:17.867 回答
-2
$line = array();
$lines = array();

$line['Boys'] = "School day, school day, teacher's golden ru";
$line['Kyle'] = "Ah, damn it! My little brother's trying to follow me to school, again.";

$lines['lines'] = $line;

祝你好运!

于 2013-11-12T15:53:45.923 回答