繁体   English   中英

使用PHP从MySQL结果输出复杂的JSON

[英]Outputting complex JSON from a MySQL result with PHP

我刚刚完成了Sencha Touch教程,效果很好。 我目前正在使用PHP将MySQL数据库中的静态JSON数据文件(本教程使用)转换为动态生成的数据(JSON)文件的过程。 本教程中使用的JSON文件(位于下面的示例文件的链接)结构复杂,我在将SQL结果转换为本教程中使用的JSON格式时遇到问题。 到源代码的链接在下面列出。 重点关注JSON文件(第三个链接)。 如果我可以简单地复制此文件,那么该项目的其余部分将为我工作。

Sencha Touch教程位于: http : //www.sencha.com/learn/intro-to-the-nested-list-component/

该项目的所有代码都可以位于(我只允许发布两个链接,希望您可以解释下面的链接):github dot com / nelstrom / Sencha-Touch-nested-list-demo

可以在以下位置查看静态JSON数据文件的示例: https : //github.com/senchalearn/Nested-list-demo/blob/master/data/albums.json

我有一个数据库和sql,它们以以下结构输出数据:

Genre  Artist     Album           Track               Duration 
ROCK   MUSE       Absolution      Intro               0:23
ROCK   MUSE       Absolution      Apolcalypse Please  4:13
ROCK   MUSE       The Resistance  Uprising            5:03
ROCK   SEVENDUST  Next            Hero                3:48
FUNK   PRIMUS     Antipop         The Antipop         5:33
FUNK   PRIMUS     Antipop         Ballad of Bodacious 2:29

我有以下php输出JSON,但格式不正确,不幸的是,它与我能得到的接近-抱歉,我的PHP有点平均:)

$result = mysql_query($query,$link) or die('Errant query:  '.$query);
$model = array();

if(mysql_num_rows($result)) {
    while($e = mysql_fetch_assoc($result)) {
        $model['Genre'] = $e['Genre'];
        $model['Artist'] = $e['Artist'];
        $model['Album'] = $e['Album'];
        $model['items'][] = array(
                        'text' => $e['Track'],
                        'duration' => $e['Duration']
        );
    }
}  

header('Content-type: application/json');
echo json_encode(array('items'=>$model));}

这是上面的PHP代码输出的JSON的示例:

{
    "items": {
        "Genre": "ROCK",
        "Artist": "MUSE",
        "Album": "Absolution",
        "items": [
            {
                "text": "Intro",
                "duration": "0:23"
            },
            {
                "text": "Apolcalypse Please",
                "duration": "4:13"
            }
        ]
    }
}

不幸的是,此JSON格式不正确。 主要问题是在正确的位置循环并使用方括号'['']'。 我在下面提供了一个简短的示例:

    {
    "items": [
     {
       "model": "Genre",
       "items": [
         {
           "model": "Artist",
           "items": [
             {
               "model": "Album",
               "items": [
                {
                  "model": "Track",
                  "duration": 96,
                  "text": "Introduction",
                  "items": [

                  ],
                  "info": "",
                  "leaf": true
                 },
                 {
                  "model": "Track",
                  "duration": 155,
                  "text": "Please Accept My Love",
                  "items": [

                  ],
                  "info": "",
                  "leaf": true
                }
              ],
              "text": "Live in Cook County Jail",
              "info": "<p>Live in Cook County Jail is a 1971 live album by B.B. King recorded in Cook County Jail, Chicago, Illinois. It was ranked as number 499 in the book version of Rolling Stone's 500 Greatest Albums of All Time.</p>",
              "leaf": true
            }
          ],
          "text": "B.B.King",
          "info": "<p>Riley B. King aka B. B. King (born September 16th, 1925 in Itta Bena, Mississippi) is a well known American blues guitarist and songwriter. He is among the most respected electric guitarists. </p><p>One of King’s trademarks is naming his guitar (Gibson ES335) “Lucilleâ€. In the 1950s in a bar in Twist, Arkansas two men got into a fight, accidentally knocking over a bucket of burning kerosene (used for heating) and setting the establishment on fire. Risking his life, B.B. King ran back into the collapsing building to retrieve his guitar.</p>",
          "leaf": false
        },
      ],
      "text": "Blues",
      "info": "",
      "leaf": false
    }
  ]
} 

预先感谢您查看此内容,如果您遇到了麻烦,抱歉,但是我只是想确保已包含所有内容。 如果您需要更多信息,请告诉我。

亲切的问候

我要做的第一件事是尝试重新创建JSON格式化数据。 快速测试

$array = array(
'items' => array(
    array(
    'model' => 'Genre',
    'items' => array(
        array(
        'model' => 'Artist',
        'items' => array(
            'model' => 'Album',
            'items' => array(array())
        )
        )
    )
    )
)
);
$json = json_encode( $array );
var_dump( $json );

这将提供与您所需类似的JSON输出。

然后,您需要将数据库中的数据放入相关格式的数组中。 为了避免多次遍历正在构建的数组(随着数组变大,可能需要一段时间),我将其分为两个步骤进行。

第一

$tempData = array();
while($e = mysql_fetch_assoc($result)) {
    $tempData[$e['Genre']][$e['Artist']][$e['Album']][$e['Track']] = $e['Duration']
}

然后,您应该能够遍历$ tempArray并以正确的格式构建一个数组以创建JSON。

这很棘手。 那是一个非常糟糕的数据模型。

您需要添加一些字段,并可能需要做一些工作,但是请尝试一下。

if(mysql_num_rows($result)) {
    while($e = mysql_fetch_assoc($result)) {
        $genreExisted = 0;
        $albumExisted = 0;
        foreach ($model['items'] as $genreKey => $genre) {
            if ($e['Genre'] == $genre['text']) {
                $genreExisted = 1;
                foreach ($genre['items'] as $albumKey => $album) {
                    if ($e['Album'] == $album['text']) {
                        $albumExisted = 1;
                        //add a new track
                        $model['items'][$genreKey]['items'][$albumKey]['items']["model"] = $e['Track'];
                        $model['items'][$genreKey]['items'][$albumKey]['items']["duration"] = $e['Duration'];
                    }
                }
                if ($albumExisted != 1) {
                    //add an album inside the genre
                    $model['items'][$genreKey]['items'][]["model"] = "Album";
                    $model['items'][$genreKey]['items'][]["text"] = $e['Album'];
                }
            }    
        }
        if ($genreExisted != 1) {
            //add a new genre
            $model['items'][]["model"] = "Genre";
            $model['items'][]["text"] = "Blues";
        }
    }
}

您可以使用以下代码一次性完成此操作。 只需确保您的数据按流派,艺术家,专辑,曲目排序即可。

if(mysql_num_rows($result)) {
   $curr_genre = $curr_artist = $curr_album = $curr_track = '';
   $model = $track = $album = $artist = $genre = array();
   $first_row = 1;
   while ($e = mysql_fetch_assoc($result))
        // every time track changes, create new array and insert into album
        $track['model'] = 'Track';
        $track['info'] = "";
        $track['text'] = $e['Track'];
        $track['duration'] = $e['Duration'];
        $track['leaf'] = TRUE;
        $album['items'][] = $track;
        $track = array();

        // every time album changes, create new array and insert into artist
    if ($curr_album != $e['Album']) {
        $album['model'] = 'Album';
        $album['info'] = "";
        $album['text'] = $curr_album;
        $album['leaf'] = FALSE;
        if (!$first_row) 
    {
        // pop the last item as it's taken one from the next album
        $new_item = array_pop(&$album['items']);
        $artist['items'][] = $album;
        $album = array();
        $album['items'][] = $new_item;
        }
        $curr_album = $e['Album'];

        }

        // every time artist changes, create new array and insert into genre
    if ($curr_artist != $e['Artist']) {
        $artist['model'] = 'Artist';
        $artist['info'] = "";
        $artist['text'] = $curr_artist;
        $artist['leaf'] = FALSE;
        if (!$first_row) 
    {
        $genre["items"][] = $artist;
    $artist = array();
    }
    $curr_artist = $e['Artist'];
    }


        // every time genre changes, create new array and insert into model
    if ($curr_genre != $e['Genre']) {
        $genre['model'] = 'Genre';
        $genre['text'] = $curr_genre;
        $genre['left'] = FALSE;
        if (!$first_row) 
    {
        $model["items"][] = $genre;
    $genre = array();
    }

    $curr_genre = $e['Genre'];
        }

        if ($first_row) {
            $first_row = 0;
        }
    }
  }  
    // now just process the last row

        $album['model'] = 'Album';
        $album['info'] = "";
        $album['text'] = $curr_album;
        $album['leaf'] = FALSE;
        $album['items'][] = $track;

        $artist['model'] = 'Artist';
        $artist['info'] = "";
        $artist['text'] = $curr_artist;
        $artist['leaf'] = FALSE;
        $artist['items'][] = $album;

        $genre['model'] = 'Genre';
        $genre['text'] = $curr_genre;
        $genre['left'] = FALSE;
        $genre["items"][] = $artist;

        $model['items'][] = $genre;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM