Merging two json in PHP - php

I have two json's
First one is
[{"COLUMN_NAME":"ORDER_NO","COLUMN_TITLE":"Order Number"}
,{"COLUMN_NAME":"CUSTOMER_NO","COLUMN_TITLE":"Customer Number"}]
Second one is
[{"COLUMN_NAME":"ORDER_NO","DEFAULT_VALUE":"1521"},
{"COLUMN_NAME":"CUSTOMER_NO","DEFAULT_VALUEE":"C1435"}]
I want to merge them and have a json like
[{"COLUMN_NAME":"ORDER_NO","COLUMN_TITLE":"Order Number","DEFAULT_VALUE":"1521"}
,{"COLUMN_NAME":"CUSTOMER_NO","COLUMN_TITLE":"Customer Number","DEFAULT_VALUEE":"C1435"}]
is there a way to merge them? It is also OK for me if a stucture change in JSON is required
thanks.

Something like this should work:
json_encode(
array_merge(
json_decode($a, true),
json_decode($b, true)
)
)
or the same as one-liner:
json_encode(array_merge(json_decode($a, true),json_decode($b, true)))
array_merge in official PHP documentation
json_decode in official PHP documentation
EDIT: try adding true as second parameter to json_decode. That'll convert objects to associative arrays.
EDIT 2: try array-merge-recursive and see my comment below. Sorry have to log out now :(
This looks like a full correct solution: https://stackoverflow.com/a/20286594/1466341

Managed to throw this together. There is most likely a better solution, but this is the closest I got.
$a = '[{"COLUMN_NAME":"ORDER_NO","COLUMN_TITLE":"Order Number"},{"COLUMN_NAME":"CUSTOMER_NO","COLUMN_TITLE":"Customer Number"}]';
$b = '[{"COLUMN_NAME":"ORDER_NO","DEFAULT_VALUE":"1521"},{"COLUMN_NAME":"CUSTOMER_NO","DEFAULT_VALUEE":"C1435"}]';
$r = [];
foreach(json_decode($a, true) as $key => $array){
$r[$key] = array_merge(json_decode($b, true)[$key],$array);
}
echo json_encode($r);
returns,
[{"COLUMN_NAME":"ORDER_NO","DEFAULT_VALUE":"1521","COLUMN_TITLE":"Order Number"},
{"COLUMN_NAME":"CUSTOMER_NO","DEFAULT_VALUEE":"C1435","COLUMN_TITLE":"Customer Number"}]

This works like a charm for me
json_encode(array_merge(json_decode($a, true),json_decode($b, true)))
here is a full example
$query="SELECT * FROM `customer` where patient_id='1111118'";
$mysql_result = mysql_query($query);
$rows = array();
while($r = mysql_fetch_assoc($mysql_result)) {
$rows[] = $r;
}
$json_personal_information=json_encode($rows);
//echo $json_personal_information;
$query="SELECT * FROM `doctor` where patient_id='1111118'";
$mysql_result = mysql_query($query);
$rows = array();
while($r = mysql_fetch_assoc($mysql_result)) {
$rows[] = $r;
}
$json_doctor_information=json_encode($rows);
//echo $json_doctor_information;
echo $merger=json_encode(array_merge(json_decode($json_personal_information, true),json_decode($json_doctor_information, true)));

This worked to me!
$dados1 = json_encode(array('data'=>'1'));
$dados2 = json_encode(array('data2'=>'2'));
echo json_encode(array_merge(json_decode($dados1, true),json_decode($dados2, true)));

Related

how can produce json array with while in php

i want return my data from mysql to json array with do while loop.
when i return one record with json it is well. but i want return list of array in one json array.
how can do that with index in while? my code have error and i don't know how can do it. with one record it is well but more can't.
$json="array(";
do{
$json=."'$row_query['id']'=>array('fname'=>$row_query['fname'],'lname'=>$row_query['lname']),";
} while ($row_query = mysqli_fetch_assoc($query));
json=.")";
echo json_encode($json,JSON_UNESCAPED_UNICODE);
There's no need to add quotes, brackets, parentheses or whatever. json_encode function will do it for you. Just provide an array to it:
$json = [];
while ($row_query = mysqli_fetch_assoc($query)) {
$json[$row_query['id']] = [
'fname'=>$row_query['fname'],
'lname'=>$row_query['lname'],
];
}
echo json_encode($json,JSON_UNESCAPED_UNICODE);
This is the most super easy version. You may try this.
$json = new array();
do{
array_push($json,$row_query);
} while ($row_query = mysqli_fetch_assoc($query));
or
$json = [];
do{
$json[] = $row_query;
} while ($row_query = mysqli_fetch_assoc($query));
Atlast encode your json variable.
$json = json_encode($json);
echo $json;

PHP Sorting results of a Loop and displaying onscreen

I was wondering if someone could point me in the right direction with a coding issue Im having.
I am running a while loop in PHP comparing a post code to another and each run of the loop generates distance data. What Id like to do is then sort this data and display it.
Usually I'd throw everything into a MySQL database then sort that way but I think thats over kill.
Here's an example of the loop :
while($row = mysql_fetch_array($result))
{
$info = get_driving_information($_POST['customerpostcode'], $row[instructor_postcode]);
echo $row['instructor_name'] . " - " . $info['distance'];
}
I know this is probably PHP 101 but Ive never had to do anything like this before and am not sure how.
Thanks in advance for reading,
Rik
I think this is what you mean:
$rows = array();
while($row = mysql_fetch_array($result))
{
$info = get_driving_information($_POST['customerpostcode'], $row[instructor_postcode]);
$row['distance'] = $info['distance']; // store it in the array
$rows[] = $row;
}
Then use usort to sort the $rows array by the distance key.
What I'd recommend here is storing each distance result in an array and then apply a sort to the array. For example:
$distances = array();
while($row = mysql_fetch_array($result))
{
$info = get_driving_information($_POST['customerpostcode'], $row[instructor_postcode]);
$distances[$info['distance']] = $row['instructor_name'] . " - " . $info['distance'];
}
if(ksort($distances)) {
foreach($distances as $key=>$value) {
echo $value;
}
}
Note that my solution will not work for you if an exact distance appears more than once in the array; If that seems likely then you might need a different array-based solution.
For more information on array sorting, see Sorting Arrays in the PHP manual.
$data = array();
while($row = mysql_fetch_assoc($result)) {
$info = get_driving_information($_POST['customerpostcode'], $row['instructor_postcode']);
$data[$row['instructor_name']] = $info['distance'];
}
asort($data);
foreach ($data as $instructor => $distance) echo "$instructor - $distance<br />\n";
This will sort by instructor name. If you need to sort by distance, just reverse the way data is stored in the temporary array, I.E. $data[$row['distance']] = $info['instructor_name'];.
This will not work if the value you use as the temporary array key appears more than once, for that you would have to use array_multisort().
$data = $instructors = $distances = array();
for ($i = 0; $row = mysql_fetch_assoc($result); $i++) {
$info = get_driving_information($_POST['customerpostcode'], $row['instructor_postcode']);
$instructors[$i] = $row['instructor_name'];
$distances[$i] = $row['distance'];
$data[$i] = array('instructor'=>$row['instructor_name'],'distance'=>$info['distance']);
}
array_multisort($instructors,SORT_DESC,$distances,SORT_ASC,$data);
foreach ($data as $entry) echo "{$entry['instructor']} - {$entry['distance']}<br />\n";
This will work even if you have same instructor_name or distances several time in the array. Additionally buy modifying cmp() function you can sort whole thing by any other criteria.
$drivers = array();//initialising an array
while($row = mysql_fetch_array($result))
{
$info = get_driving_information($_POST['customerpostcode'], $row[instructor_postcode]);
$drivers[]=row;//adding new item to array
}
$drivers = usort($drivers,'cmp'); // sorting array using custom comparison function "cmp()"
foreach ($drivers as $driver) //printing results
echo $driver['instructor_name'] . " - " . $driver['distance'];
//custom comparison function
function cmp($a, $b) //returns +1 if $a > $b, -1 if $a < $b, else returns 0
{
if ($a['distance']>$b['distance'])
return 1;
if ($a['distance']<$b['distance'])
return -1;
return 0;
//quicker solution is to "return $a['distance']-$b['distance'];"
}

How to index the result of a mySql query as an array of array?

If I need to select and use information of every element of a table in a database the procedure would be this:
$query = "...mySql query...";
$query_result = mysql_query($query) or die (mysql_error());
Then if I wished to access the fields of the result I would use the function mysql_fetch_array() and access them like this:
$query_result_array = mysql_fetch_array($query_result);
echo $query_result_array['field_1'];
....
echo $query_result_array['field_i'];
....
But since more elements could be returned by the query I would like to access every single of them with an array indexed from 0 to mysql_num_rows($query_result).
As an example:
echo $query_result_array['field_i'][0];
....
echo $query_result_array['field_i'][mysql_num_rows($query_result)];
should print for every selected element of the table the value of field i.
Is there a function that will do the job for me?
If not, any suggestions on how to do it?
Thanks in advance for help.
This may be an alternative
$res = mysql_query("..SQL...");
$arr = array();
while ($row = mysql_fetch_assoc($res)) {
$arr[] = $row;
}
var_dump($arr);
Or
$res = mysql_query("..SQL...");
for
(
$arr = array();
$row = mysql_fetch_assoc($res);
$arr[] = $row
);
var_dump($arr);
I don't think there is such a method; you have to do it yourself.
try with something like:
$res = mysql_query("..mySql query...");
$arr = array();
while ($row = mysql_fetch_assoc($res)) {
$query_result_array[] = $row;
}
then you access your data like:
echo $query_result_array[0]['field_i'];
based on 2 previous answers, those authors assuming that usual SO author is familiar with such a thing as creating a function
function sqlArr($sql) { return an array consists of
$ret = array();
$res = mysql_query($sql) or trigger_error(mysql_error()." in ".$sql);
if ($res) {
while ($row = mysql_fetch_assoc($res)) {
$ret[] = $row;
}
}
return $ret;
}
$array = sqlArr("SELECT * FROM table");
foreach ($array as $row) {
echo $row['name'],$row['sex'];
}
this resulting array have different structure from what you asked, but it is way more convenient too.
if you still need yours unusual one, you have to tell how you gonna use it

Create and array index and value from the two array elements in a while loop

while($info5 = mysql_fetch_array($result)){
$namelist[] = $info5["name"];
$idlist[] = $info5["id"]
}
I want an array which has the entries of the array idlist as it's index and entries of the array namelist as it's values.
Is there a short way to do this?
Like this, if I understand your request. Use $info['id'] as the array key to the accumulating array $namelist (or whatever you decide to call it)
while($info5 = mysql_fetch_array($result)){
$namelist[$info['id']] = $info5["name"];
}
i'm not sure i understand your question but probably something like this should be fine.
while($info5 = mysql_fetch_array($result)){
$values[$info5['id']] = $info5;
}
$result = array();
while($info5 = mysql_fetch_array($result))
{
$id = $info5['id'];
$name = $info5['name'];
$result[$id] = $name;
}
This should give the output array $result you want, if I understood correctly.
You can use array_combine as long as the arrays have the same number of values:
$result = false;
if (count($idlist) == count($namelist))
$result = array_combine($idlist, $namelist);
Check out the docs: http://www.php.net/manual/en/function.array-combine.php
But, I also wonder why you don't just do it in the while loop:
$values = array();
$namelist = array();
$idlist = array();
while($info5 = mysql_fetch_array($result)){
$namelist[] = $info5["name"];
$idlist[] = $info5["id"]
// this is the combined array you want?
$values[$info5["id"]] = $info5["name"];
}

format mysql data in array

I am pulling data from my database and trying to encode into JSON data using json_encode. But to make it easier to read in my android app. I was hopping to format it differently then I am currently doing. Please see bottom encode string example. Any help would be great. Thanks in Advance.
$result = $db->query($query);
while($info = mysql_fetch_array($result))
{
$content[] = $info;
}
$count = count($content);
$result=array();
for($i=0;$i<$count;$i++)
{
$result[id][] = $content[$i]['imageID'];
$result[name][] = $content[$i]['Name'];
$result[thumb][] = $content[$i]['Thumb'];
$result[path][] = $content[$i]['Path'];
}
echo json_encode($result);
{"id":["1","2","3"],"name":["Dragon","fly","bug"],"thumb":["thm_polaroid.jpg","thm_default.jpg","thm_enhanced-buzz-9667-1270841394-4.jpg"],"path":["polaroid.jpg","default.jpg","enhanced-buzz-9667-1270841394-4.jpg"]}
But I am trying to format my array like so when it is encoded by json_encode.
[{"id":"1","name":"Dragon","thumb":"thm_polaroid.jpg","path":"polaroid.jpg"},{"id":"2","name":"Fly","thumb":"thm_default.jpg","path":"default.jpg"},{"id":"3","name":"Bug","thumb":"thm_enhanced-buzz-9667-1270841394-4.jpg","path":"enhanced-buzz-9667-1270841394-4.jpg"}]
Well, there is a problem. This is not valid JSON:
{"image":["1","Dragon","thm_polaroid.jpg","polaroid.jpg"],
"image":["2","fly","thm_default.jpg","default.jpg"]}
A JSON object can only have one value per unique key. This means that your latter image key would clobber the value of the former.
If you are content with this, however:
[["1","Dragon","thm_polaroid.jpg","polaroid.jpg"],
["2","fly","thm_default.jpg","default.jpg"]]
Then you can simply use mysql_fetch_row:
$result = $db->query($query);
while($info = mysql_fetch_row($result))
{
$content[] = $info;
}
echo json_encode($content);
Side Note:
Generally, in PHP, it is best to use foreach( $arr as $val ) (or $arr as $key => $val). for loops should be limited to when they are strictly necessary.
You need to add the iterator $i to the setting array
for($i=0;$i<$count;$i++)
{
$result[$i][id] = $content[$i]['imageID'];
$result[$i][name] = $content[$i]['Name'];
$result[$i][thumb] = $content[$i]['Thumb'];
$result[$i][path] = $content[$i]['Path'];
}
<?
$result = $db->query($query);
while($info = mysql_fetch_array($result))
$content[] = $info;
$result=array();
$count = count($content);
for ($x=0;$x<$count;++$x)
{
$result[$x][] = $content[$x]['imageID'];
$result[$x][] = $content[$x]['Name'];
$result[$x][] = $content[$x]['Thumb'];
$result[$x][] = $content[$x]['Path'];
}
echo json_encode($result);
?>

Categories