trying to combine these two json arrays in php - php

I've tried things like json_combine and array_merge but I can't figure out how to do this.
$query2 = "SELECT DISTINCT cat_id,cat_name FROM review WHERE user_id = ? AND public_or_private = 0";
$stmt2 = $con->prepare($query2) or die(mysqli_error($con));
$stmt2->bind_param('i', $user_id) or die ("MySQLi-stmt binding failed ".$stmt2->error);
$stmt2->execute() or die ("MySQLi-stmt execute failed ".$stmt2->error);
$result2 = $stmt2->get_result();
$array1 = array();
while ($row = mysqli_fetch_assoc($result2)) {
$array1['results'][] = $row;
}
echo json_encode($array1);
The json_encode gives me:
{"results":[{"cat_id":4,"cat_name":"dentist"}]}
And further down in my code I have:
$query3 = "SELECT DISTINCT cat_id,cat_name FROM review WHERE public_or_private = 2";
$result3 = mysqli_query($con,$query3);
$array2 = array();
while($row = mysqli_fetch_assoc($result3)) {
$array2['results'][] = $row;
}
echo json_encode($array2);
The json_encode gives me:
{
"results": [{
"cat_id": "8",
"cat_name": "dental hygienist"
}, {
"cat_id": "5",
"cat_name": "stocktaker"
}, {
"cat_id": "9",
"cat_name": "builder"
}]
}
So in total I have two json arrays:
{
"results": [{
"cat_id": 4,
"cat_name": "dentist"
}]
}
{
"results": [{
"cat_id": "8",
"cat_name": "dental hygienist"
}, {
"cat_id": "5",
"cat_name": "stocktaker"
},
{
"cat_id": "9",
"cat_name": "builder"
}
]
}
But how can I combine these into one like:
{
"results": [{
"cat_id": 4,
"cat_name": "dentist"
}, {
"cat_id": "8",
"cat_name": "dental hygienist"
}, {
"cat_id": "5",
"cat_name": "stocktaker"
},
{
"cat_id": "9",
"cat_name": "builder"
}
]
}
I tried things like:
$jsonArray = array();
foreach (array_combine( $array1, $array2 ) as $name => $value) {
$jsonArray[] = array('cat_id' => $name, 'cat_name' => $value);
}
echo $json = json_encode($jsonArray);
but still couldn't get it to work properly.

I guess you want to use array_merge_recursive instead.
echo json_encode(array_merge_recursive($array1, $array2));

Its not array_combine
You need to merge both array
$array1 = json_decode($array1, true);
$array2 = json_decode($array2, true);
$final_array = array_merge($array1['results'], $array2['results']);

Assuming you already have your arrays, you can do this:
$res1 = [
"results"=> [[
"cat_id"=> 4,
"cat_name"=> "dentist"
]]
];
$res2 = [
"results"=> [[
"cat_id"=> "8",
"cat_name"=> "dental hygienist"
], [
"cat_id"=> "5",
"cat_name"=> "stocktaker"
],
[
"cat_id"=> "9",
"cat_name"=> "builder"
]
]
];
$combinedArray = array_merge_recursive($res1, $res2);
$jsonCombinedArray = json_encode($combinedArray);
This results into
{
"results": [
{"cat_id":4,"cat_name":"dentist"},
{"cat_id":"8","cat_name":"dental hygienist"},
{"cat_id":"5","cat_name":"stocktaker"},
{"cat_id":"9","cat_name":"builder"}
]
}

Related

How to use INNER JOIN with array on second table in mysql?

I can't properly use INNER JOIN. This is the actual return output via json on php.
[
{
"id": "1",
"itinerary_customer_id": "856",
"datetime_created": "2020-04-20 19:54:16",
"documents": [
{
"id": "1",
"itinerary_id": "1",
"datetime_created": "2020-04-20 22:51:12"
},
{
"id": "2",
"itinerary_id": "1",
"datetime_created": "2020-04-20 22:51:12"
},
]
},
{
"id": "2",
"itinerary_customer_id": "857",
"datetime_created": "2020-04-20 19:54:16",
"documents": [
{
"id": "3",
"itinerary_id": "2",
"datetime_created": "2020-04-20 22:51:12"
},
{
"id": "4",
"itinerary_id": "2",
"datetime_created": "2020-04-20 22:51:12"
},
]
}
]
Its look like array json and there's possible array inside each data.
Here's my existing code.
$sql = "SELECT * FROM itinerary INNER JOIN itinerary_documents ON itinerary_documents.itinerary_id = itinerary.id WHERE itinerary_customer_id = '".$customer_id."' ";
$result = $mysql->query($sql);
if ($result->num_rows > 0) {
while ($row[] = $result->fetch_assoc()) {
$item = $row;
$json = json_encode($item);
}
}else{
$item = array("error"=> true, "message"=> "No Itinerary found.");
$json = json_encode($item);
}
echo $json;

json data formating wrapped inside a var

I have a json data generated with the following php code
$index = array();
foreach($rows as $row)
{
$row['data'] []= (object) [];
$index[$row['cat_id']] = $row;
}
// build the tree
foreach($index as $id => &$row)
{
if ($id === 0) continue;
$parent = $row['parent'];
$index [$parent]['children'][] = &$row;
}
unset($row);
// obtain root node
$index = $index[0]['children'][0];
$json_data = json_encode($index, JSON_PRETTY_PRINT);
which produces the following json
{
"cat_id": "1",
"id": "RT",
"name": "root",
"parent": "0",
"url": "www.test.com",
"data": [
{}
],
"children": [
{
"cat_id": "4",
"id": "CI.001",
"name": "Test2",
"parent": "2",
"url": "www.test.com",
"data": [
{}
]
}
what i want is the output to be like this
var something = [{
"cat_id": "1",
"id": "RT",
"name": "root",
"parent": "0",
"url": "www.test.com",
"data": [
{}
],
"children": [
{
"cat_id": "4",
"id": "CI.001",
"name": "Test2",
"parent": "2",
"url": "www.test.com",
"data": [
{}
]
}];
I have looked through the web with some suggesting that it is not json but php array i'm new to json. How can I solve this ?
Here is is my solution at the moment.
ob_start();
echo "var javascript_array = [". $json_data . "];\n";
$content = ob_get_contents();
file_put_contents('../core/json/tree.js', $content);
Any suggestions and improvements will be appreciated.

Fetch particular data from duplicated record in PHP

I just wanted to know is there a possibility to get specific columns from duplicated row in PHP-MySQL connection and use them to the existing data in JSON?
/...db connection etc.
if ($statement->execute())
{
$response["lecturer"] = array();
while($row = $statement->fetch(PDO::FETCH_ASSOC))
{
$lecturer = array();
$lecturer["id"] = $row["lecturerid"];
$lecturer["image"] = $row["l_image"];
$lecturer["degree"] = $row["degree"];
$lecturer["name"] = $row["l_name"];
$lecturer["surname"] = $row["surname"];
$lecturer["field"] = array();
$lecturer["field"]["fieldid"] = $row["fieldid"];
$lecturer["field"]["name"] = $row["f_name"];
array_push($response["lecturer"], $lecturer);
}
}
/... json_encode etc.
So, there can be a situation, where one lecturer has 2 different fields, and I'm getting something like this:
{
"lecturer": [
{
"id": 1,
"image": "http://...",
"degree": "PhD",
"name": "John",
"surname": "Doe",
"field": {
"fieldid": 13,
"name": "field1"
}
},
{
"id": 1,
"image": "http://...",
"degree": "PhD",
"name": "John",
"surname": "Doe",
"field": {
"fieldid": 14,
"name": "field2"
}
},
Instead of that, I would like to get JSON:
{
"lecturer": [
{
"id": 1,
"image": "http://...",
"degree": "PhD",
"name": "John",
"surname": "Doe",
"field": {
"fieldid": 13,
"name": "field1",
"fieldid": 14,
"name": "field2"
}
},
In the MySQL database there are two tables: lecturer, and field, but also lecturer_field table, where I have relation between lecturerid and fieldid.
As i was pointed out, it's impossible to declare similar named field in json object:
"field": {
"fieldid": 13,
"name": "field1",
"fieldid": 14,
"name": "field2"
}
Valid case is
"field": [{
"fieldid": 13,
"name": "field1",
},
{
"fieldid": 14,
"name": "field2"
}]
You can do that in this way:
if ($statement->execute())
{
$indexedLecturers = array();
while($row = $statement->fetch(PDO::FETCH_ASSOC))
{
$lid = $row["lecturerid"];
if (isset($indexedLecturers[$lid])) {
array_push($indexedLecturers[$lid]["field"], array(
"fieldid" => $row["fieldid"],
"name" => $row["f_name"],
));
} else {
$lecturer = array();
$lecturer["id"] = $lid;
$lecturer["image"] = $row["l_image"];
$lecturer["degree"] = $row["degree"];
$lecturer["name"] = $row["l_name"];
$lecturer["surname"] = $row["surname"];
$lecturer["field"] = array();
array_push($lecturer["field"], array(
"fieldid" => $row["fieldid"],
"name" => $row["f_name"],
));
$indexedLecturers[$lid] = $lecturer;
}
}
$response['lecturer'] = array_values($indexedLecturers);
}

Structure JSON output with PHP

I am trying to generate a JSON output from the DATABASE with MySQL.
The result that I want is that I want an array around two matching ID's found in the tabel in the database.
To visualise what I wish to achieve here is my code:
This is my query
$sql = "SELECT * FROM `flower_garden` WHERE `id_flower` IN (0, 1)";
$result = mysql_query($sql);
while($record = mysql_fetch_assoc($result)) {
$rows[] = $record;
}
print json_encode($rows);
This is the JSON result I wish to achieve:
(What I want)
[
[
"id": "1",
"id_flower": "3",
"Title": "rose",
"Price": 1.25,
"Number": 15
},
{
"id": "2",
"id_flower": "3",
"Title": "daisy",
"Price": 0.75,
"Number": 25
}
],
[
{
"id": "3",
"id_flower": "6",
"Title": "rose",
"Price": 1.25,
"Number": 15
},
{
"id": "4",
"id_flower": "6",
"Title": "daisy",
"Price": 0.75,
"Number": 25
}
]
]
Visual result:
So, I want the matching ID's (in this case id_flower) put in one array.
This is the result I get:
(What I get)
[
[
"id": "1",
"id_flower": "3",
"Title": "rose",
"Price": 1.25,
"Number": 15
},
{
"id": "2",
"id_flower": "3",
"Title": "daisy",
"Price": 0.75,
"Number": 25
},
{
"id": "3",
"id_flower": "6",
"Title": "rose",
"Price": 1.25,
"Number": 15
},
{
"id": "4",
"id_flower": "6",
"Title": "daisy",
"Price": 0.75,
"Number": 25
}
]
]
Visual result:
Try this
foreach ($rows as $key => $val) {
$return[$val['id_flower']][] = $val;
}
echo json_encode($return);
Please note I have not tested it.
$sql = "SELECT * FROM `flower_garden` WHERE `id_flower` IN (0, 1)";
$result = mysql_query($sql);
$rows = array();
while($record = mysql_fetch_assoc($result)) {
array_push($rows[$record["id_flower"]], $record);
}
$result = array();
foreach($rows as $k => $v){
array_push($result, $v);
}
echo json_encode($result);
test yourself !

php json_encode formatting results?

I have:
$all = array(
array('id'=>1, 'cat'=>'Main','type'=>'Name0'),
array('id'=>2, 'cat'=>'Main','type'=>'Name1'),
array('id'=>3, 'cat'=>'Main','type'=>'Name3'),
array('id'=>4, 'cat'=>'Main','type'=>'Name4'),
array('id'=>5, 'cat'=>'Secondary','type'=>'Name5'),
array('id'=>6, 'cat'=>'Secondary','type'=>'Name6'),
array('id'=>7, 'cat'=>'Secondary','type'=>'Name7'),
array('id'=>8, 'cat'=>'Other','type'=>'Name8'),
array('id'=>9, 'cat'=>'Other','type'=>'Name9'),
array('id'=>10, 'cat'=>'Other','type'=>'Name10'),
array('id'=>11, 'cat'=>'Other','type'=>'Name11'),
);
$result = array();
foreach($all as $array){
$result[$array['cat']][] = array('id'=>$array['id'],'type'=>$array['type']);
}
$json_type = json_encode($result);
Which returns:
{"Main":[{"id":"1","type":"name1"},{"id":"2","type":"name2"},{"id":"3","type":"name3"},{"id":"4","type":"name4"}],"Secondary":[{"id":"5","type":"name5"},{"id":"6","type":"name6"},{"id":"7","type":"name7"}],"Other":[{"id":"8","type":"name8"},{"id":"9","type":"name9"},{"id":"10","type":"name10"},{"id":"11","type":"name11"}]}
But I need it to return as:
[
{
"text": "Main",
"children": [
{
"id": "1",
"text": "name1"
},
{
"id": "2",
"text": "name2"
},
{
"id": "3",
"text": "name3"
},
{
"id": "4",
"text": "name4"
}
]
},
{
"text": "Secondary",
"children": [
{
"id": "5",
"text": "name5"
},
{
"id": "6",
"text": "name6"
},
{
"id": "7",
"text": "name7"
}
]
},
{
"text": "Other",
"children": [
{
"id": "8",
"text": "name8"
},
{
"id": "9",
"text": "name9"
},
{
"id": "10",
"text": "name10"
},
{
"id": "11",
"text": "name11"
}
]
}
]
To work with the select2 JQuery plugin, I'm working with.
the 'children' name doesn't matter, I think that's just a placeholder so it gets parsed correctly. I'm not sure how I would go about it, I've been trying str_replace() but even that hasn't been working out so great.
I would to it in 2 loops. The first one to group results by category, the 2nd one to format it to fit your needs:
$temp = array();
foreach($all as $array){
if (!isset($temp[$array['cat']])) {
$temp[$array['cat']] = array();
}
$temp[$array['cat']][] = array('id'=>$array['id'], 'type'=>$array['type']);
}
$result = array();
foreach ($temp as $key=>$value) {
$result[] = array('text'=>$key, 'children'=>$value);
}
echo json_encode($result);
This produces the following output:
[{"text":"Main","children":[{"id":1,"type":"Name0"},{"id":2,"type":"Name1"},{"id":3,"type":"Name3"},{"id":4,"type":"Name4"}]},{"text":"Secondary","children":[{"id":5,"type":"Name5"},{"id":6,"type":"Name6"},{"id":7,"type":"Name7"}]},{"text":"Other","children":[{"id":8,"type":"Name8"},{"id":9,"type":"Name9"},{"id":10,"type":"Name10"},{"id":11,"type":"Name11"}]}]

Categories