将新的php数组密钥传递给json

时间:2014-11-15 13:52:16

标签: php json

我有2个表用户(id,userid,fn,ln)和userdetails(id,userid,image,history,location,activity) 我已经为第一个表写了一个查询来检索所有数据,我只想要从第二个表中获取历史和位置。

我检索了数组,然后将其发送到json_encode。 现在我想检索历史记录,位置并创建新的密钥历史记录,并且我想将历史记录位置值添加到历史记录密钥。

我需要查询和json格式。

  • 对于我需要检索的特定用户是自己的历史记录 在两个表中共享用户ID 提前致谢

    $ sth = mysql_query(" SELECT * FROM users"); $ result = mysql_fetch_assoc($ sth);     $ I = 0;     foreach($ result as $ data){         $ final_array [$ i] [' id'] = $ data [' id'];         $ final_array [$ i] [' email'] = $ data [' email'];         $ final_array [$ i] [' fname'] = $ data [' fname'];         $ final_array [$ i] [' lname'] = $ data [' lname'];

        $sth2 = mysql_query("SELECT id,places,act FROM user_dates WHERE user_id= '".$data['email']."'");
        $result2 = mysql_fetch_assoc($sth2);
        $j=0;
        $history_array = array();
        foreach($result2 as $data2) { 
          $history_array[$j] = array("id" => $data2['id'],"places" => $data2['places'], "act " => $data2['act ']);
          $j++;
        }
        $final_array[$i]['history'] = $history_array;
    
    
        $i++;
    } 
    echo json_encode($final_array);
    

[     {         " id":" 81",         " user_id":" 2011",         " fn":" asd。",         " ln":" wer",         "历史":[             {                 " id":" 350",                 "历史":" make1",                 "位置":" qwe"             }         ]     },     {         " id":" 82",         " user_id":" 2012",         " fn":" asd1",         " ln":" wer1",         "历史":[             {                 " id":" 350",                 "历史":" make2",                 "位置":" qwe2"             }         ]     } ]

1 个答案:

答案 0 :(得分:0)

Userdetails表每个用户包含multiple records。因此,您需要执行子查询并获取结果,然后形成mulch-dimensional array。最后,encode as a JSON

$sth = $dbh->prepare("SELECT * FROM users");
$sth->execute();
$result = $sth->fetchAll();

$i=0;
foreach($result as $data) { 
    $final_array[$i]['id'] = $data['id'];
    $final_array[$i]['userid'] = $data['userid'];
    $final_array[$i]['fn'] = $data['fn'];
    $final_array[$i]['ln'] = $data['ln'];

    $sth2 = $dbh->prepare("SELECT location,activity FROM userdetails WHERE userid= ".$data['id']."");
    $sth2->execute();
    $result2 = $sth2->fetchAll();
    $j=0;
    $history_array = array();
    foreach($result2 as $data2) { 
      $history_array[$j] = array("location" => $data2['location'], "activity " => $data2['activity ']);
      $j++;
    }
    $final_array[$i]['history'] = $history_array;


    $i++;
} 
echo json_encode($final_array);