解析从数据库发送的数组

时间:2015-03-22 21:49:46

标签: php html arrays

您好我想知道如何尝试解析从数据库中检索到的数据:

[
   {
      "q_id":"1",
      "type":"for",
      "author":"kappa420",
      "question":"what is the meaning of life?",
      "answer":"good question."
   },
   {
      "q_id":"2",
      "type":"recursive",
      "author":"kappa420",
      "question":"If only you knew",
      "answer":"That I was right behind you!"
   },
   {
      "q_id":"3",
      "type":"while",
      "author":"kappa420",
      "question":"who are you?",
      "answer":"ha-HA!"
   },
   {
      "q_id":"5",
      "type":"testtyte",
      "author":"testauthor",
      "question":"testquestion",
      "answer":""
   },
   {
      "q_id":"6",
      "type":"testtyte",
      "author":"testauthor",
      "question":"testquestion",
      "answer":"testanswer"
   },
   {
      "q_id":"7",
      "type":"public int add( int num1,",
      "author":"",
      "question":"Given two numbers the user must be able to add these numbers. ",
      "answer":" add(5,4) = 9\r\n add(2,3) = 5"
   },
   {
      "q_id":"8",
      "type":"public int add( int num1,",
      "author":"",
      "question":"Given two numbers the user must be able to add these numbers. ",
      "answer":" add(5,4) = 9\r\n add(2,3) = 5"
   },
   {
      "q_id":"9",
      "type":"dasdsa",
      "author":"",
      "question":" adddfa",
      "answer":" asdfs"
   },
   {
      "q_id":"10",
      "type":"adfafd",
      "author":"",
      "question":" dsadsf",
      "answer":" saddasf"
   },
   {
      "q_id":"11",
      "type":"adsf",
      "author":"",
      "question":" adsfs",
      "answer":" dsadsf"
   }
]

有没有办法获得像q_id和author这样的元素并将它们放在html属性中?

3 个答案:

答案 0 :(得分:0)

您可以使用命令JSON.parse('{JSON HERE}')将JSON解析为JavaScript数组,并且可以对数组进行for循环,并为它们创建一个HTML元素,如下所示:

$.each(arrayVar, function(i, obj) {
    $element = $('<div></div>');
    $element.attr('id') = obj['q_id'];
    $('body').append($element);
});

我希望这就是你要找的东西!

答案 1 :(得分:0)

这是一个json字符串,很容易使用php将其解析为数组。

$DataArray =  json_decode($MyDatabaseString,True);

答案 2 :(得分:-1)

                 $results = //db result
                  foreach($results as $result){
                   echo $result['q_id'];
                 }

检查http://www.w3schools.com/php/php_arrays_multi.asp Array =&gt; key =&gt;值

               // if its json

                 $results = json_decode(dbresult);
                  foreach($results as $result){
                   echo $result['q_id'];
                 }