douqiao1887 2014-09-29 20:51
浏览 67

重构由php中的while循环创建的json数组,从数据库中获取值

I am getting two JSON arrays that I need merged each time a while loop runs a fetch from my database. This is the structure array result I am getting as of now:

{id=1,cid=1,fname=Lorna,vorname=King,gender=female,dob=1985,company=helsana,monthly_amount=150},
{id=2,cid=1,fname=Brian,vorname=King,gender=male,dob=2007,company=helsana,monthly_amount=100}

I need it to look like this:

{ 1={id:1, cid:1 fname=Lorna, vorname:King, gender:female, dob:1985, company:helsana, monthly_amount:100}, 2={id:2, cid:1 fname=Brian, vorname:King, gender:male, dob:2005, company:helsana, monthly_amount:150} }

To make it easier to pick values from the array. Here is the PHP code that I am using:

<?php
include_once "conn.php";
$show= $mysqli->query("SELECT id,cid,fname,vorname,gender,dob,company,monthly_amount FROM family where cid = '1' ");
$arr = array();
while($row = $show->fetch_assoc()){
    $arr[] = $row;
}
$json_response = json_encode($arr, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP);
echo $str = substr($json_response, 1,-1);
?>

Am kinda new to this please someone help me out.

  • 写回答

1条回答 默认 最新

  • douze2890241475 2014-09-29 20:55
    关注

    You can just force it when you make the array in PHP:

    $arr = array();
    $index = 1; // Start the index where you want the count
    while($row = $show->fetch_assoc()){
        $arr[$index++] = $row;
    }
    

    Or, if you want it to match the id of the row:

    $arr = array();
    while($row = $show->fetch_assoc()){
        $arr[$row['id']] = $row;
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥15 绘制多分类任务的roc曲线时只画出了一类的roc,其它的auc显示为nan
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?