Caleb Nasio
Caleb Nasio

Reputation: 61

Merge json arrays created by a while loop in php, fetching values from a database

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.

Upvotes: 0

Views: 435

Answers (2)

BojanT
BojanT

Reputation: 801

You can use new array_column function from PHP to get what you need . Note that JSON will be of structure {id=[1,2],cid=[1,1],fname=[Lorna,Brian]... so [] instead of {}

<?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; } 
//
$final = array();
foreach ( array_keys($arr[0]) as $fieldName){
    $final[$fieldName] = array_column($arr, $fieldName);
}

$json_response =  json_encode($final,JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP);
echo $str = substr($json_response, 1,-1);

?>

Upvotes: 1

John Reid
John Reid

Reputation: 1185

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);

Upvotes: 0

Related Questions