dongpi9494 2014-09-29 12:19
浏览 120

合并由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:

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

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.

  • 写回答

2条回答 默认 最新

  • dongshendie8849 2014-09-29 12:49
    关注

    I would seriously recommend against what you're asking. There's a good reason why those results are separate.

    Anyway to answer your question here's a way - but again unless there's a specific reason why you want to so this I'd think instead about how you are handling the JSON instead.

    Here, I'm just using the first row to set up the array and then manually concatenating the data.

    <?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();
    $arr[] = $show->fetch_assoc();
    while($row = $show->fetch_assoc()){
      $arr['id'] .= ',' . $row['id'];
      $arr['cid'] .= ',' . $row['cid'];
      $arr['dob'] .= ',' . $row['dob'];
      $arr['company'] = ',' . $row['company'];
      $arr['monthly_amount'] = ',' . $row['monthly_amount'];
      $arr['vorname'] = ',' . $row['vorname'];
      $arr['fname'] = ',' . $row['fname'];
    } 
    $json_response = json_encode($arr, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP);
    echo $str = substr($json_response, 1,-1);
    
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?