1

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.

2
  • What are you using substr for? And please show the actual json output you are getting, because the example you show is not correct - its not valid json and it would not be produced from the php code you are showing Commented Sep 29, 2014 at 20:54
  • Lastly show how you are trying to use the resulting json, because i expect your current format is easily consumed Commented Sep 29, 2014 at 20:56

1 Answer 1

0

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;
}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.