PHP merge 2 Json into 1 - php

I have 2 JSON files that I would like to parse, and merge into one object and output as a single JSON.
but I can't figure out how to do and get the correct result, every time i try always get a single result like this :
[
{
"Title": "Some title for your blog",
"url": "\/post.php?id=1",
"image": "https:\/\/example.com\/images\/small\/1.jpg"
}
]
what i need is to call all the 2 json data to 1 json like this one :
[
{
"Title": "second title for your blog",
"url": "\/post.php?id=2",
"image": "https:\/\/example.com\/images\/small\/2.jpg"
}
{
"Title": "second title for your blog",
"url": "\/post.php?id=2",
"image": "https:\/\/example.com\/images\/small\/2.jpg"
}
{
"Title": "third title for your blog",
"url": "\/post.php?id=3",
"image": "https:\/\/example.com\/images\/small\/3.jpg"
}
and so on... till the end of loop
]
Here is my code :
$requestUrl="http://example.com/json1.php";
$requestUrl1="http://example.com/json2.php";
$data=file_get_contents($requestUrl);
$data1=file_get_contents($requestUrl1);
$array1 = json_decode($data);
$array2 = json_decode($data1);
$wholedata= [];
$i=0;
foreach ($array1 as $array1) {
$item['Title'] = $array1->title;
$item['url'] = $array1->url;
}
foreach ($array2 as $array2) {
$item['image'] = $array2->image;
}
$wholedata[] = $item;
$i++;
$json = json_encode($wholedata, JSON_PRETTY_PRINT);
header('Access-Control-Allow-Origin: *');
header('Content-type: Application/JSON');
echo $json;
Here's the json data :
Json 1
[
{
"title": "first title for your blog",
"url": "/post.php?id=1"
},
{
"title": "Second title for your blog",
"url": "/post.php?id=2"
},
{
"title": "Third title for your blog",
"url": "/post.php?id=3"
},
{
"title": "Fourth title for your blog",
"url": "/post.php?id=4"
},
{
"title": "Fifth title for your blog",
"url": "/post.php?id=5"
}
]
Json 2 :
[
{
"image": "https://example.com/images/small/1.jpg"
},
{
"image": "https://example.com/images/small/2.jpg"
},
{
"image": "https://example.com/images/small/3.jpg"
},
{
"image": "https://example.com/images/small/4.jpg"
},
{
"image": "https://example.com/images/small/5.jpg"
}
]

To do this with objects (as you are currently using), you can use the index of the first array to get the data from the second array. Then build the output in one go with the components from both objects and add them to your output...
$array1 = json_decode($data);
$array2 = json_decode($data1);
$wholedata= [];
foreach ($array1 as $key => $itemData) {
$wholedata[] = ['Title' => $itemData->title,
'url' => $itemData->url,
'image' => $array2[$key]->image];
}
$json = json_encode($wholedata, JSON_PRETTY_PRINT);

Try deocoding the json in an array and then merge them. Check out the official PHP documentation
array-merge - Merges two array
json_decode - Converts json into an array

Related

merge all arrays with same title [duplicate]

This question already has answers here:
How to group subarrays by a column value?
(20 answers)
PHP - Group Array by its Sub Array Value (Indexed Array)
(1 answer)
Closed 6 months ago.
i have this array in php json.
i have made it to sort array by first Characther.
but now i'm stuck on how to merge the data under the same title.
my response now is.
[
{
"title": "A",
"data": {
"id": "317",
"name": "Aesethetica"
}
},
{
"title": "A",
"data": {
"id": "318",
"name": "Astonos"
}
},
{
"title": "B",
"data": {
"id": "320",
"name": "Bourjois"
}
},
{
"title": "B",
"data": {
"id": "321",
"name": "Bioderma"
}
}
]
i need to merge all data under each same title.
something like this:
[
{
"title": "A",
"data": [
{
"id": "317",
"name": "Aesethetica"
},
{
"id": "318",
"name": "Astonos"
}
]
},
{
"title": "B",
"data": [
{
"id": "320",
"name": "Bourjois"
},
{
"id": "321",
"name": "Bioderma"
}
]
}
]
kindly help.
Thanks
i got this now:
i made this update.. but still not the needed result.
this is my php code...
$result = [];
foreach ($data as $item) {
$firstLetter = substr($item['name'], 0, 1);
$result[] = [
'title' => $firstLetter = ctype_alnum($firstLetter) ? $firstLetter : '#',
'data' => $item
];
}
foreach ($result as $key => $item) {
$arr[$item['title']][$key] = $item;
}
and this is the result.
{
"A": [
{
"title": "A",
"data": {
"brand_id": "312",
"brand_name": "Adidsa"
}
},
{
"title": "A",
"data": {
"id": "314",
"name": "Adio"
}
},
still can't find make the needed response..
This is not perfomance optimized, but shows a simple solution.
Collect all data grouped by title, then reformat the array to your expected result.
$array = json_decode($json, true);
$collect = [];
foreach($array as $item) {
$collect[$item['title']][] = $item['data'];
}
ksort($collect);
$titles = [];
foreach($collect as $title => $data) {
$names = array_column($data, 'name');
array_multisort($names, SORT_ASC, SORT_STRING, $data);
$titles[] = ['title' => $title, 'data' => $data];
}
echo json_encode($titles, JSON_PRETTY_PRINT); results in
[
{
"title": "A",
"data": [
{
"id": "317",
"name": "Aesethetica"
},
{
"id": "318",
"name": "Astonos"
}
]
},
{
"title": "B",
"data": [
{
"id": "321",
"name": "Bioderma"
},
{
"id": "320",
"name": "Bourjois"
}
]
}
]

Simplifying my JSON to build a array.

I am trying to take my JSON input and generate a easy array to search in, but it is as far as I can tell giving me some trouble.
First of, this is my JSON as is, loaded from a file:
{
"teams": [
{
"id": "1",
"boat": "Test",
"name": "Palle Test"
},
{
"id": "2",
"boat": "Test 2",
"name": "Name Test 2"
},
{
"id": "3",
"boat": "Test 3",
"name": "Name Test 3"
},
{
"id": "4",
"boat": "Test 4",
"name": "mller"
}
]
}
Is there a way to simplify this or minimise the number of arrays?
I have been using the following code to preview my array, but I am trying to get it to search for id and then print the values for id, boat and name.
$json_url = "teams.json";
$json = file_get_contents($json_url);
$data = json_decode($json, TRUE);
echo '<pre>';
print_r($data);
echo '</pre>';
This is really quite simple. There is no need to convert a perfectly good object into an array, it only makes life more complex.
The only array you have in your data structure is the teams array and that is easily processed like this
$json = '{
"teams": [
{
"id": "1",
"boat": "Test",
"name": "Palle Test"
},
{
"id": "2",
"boat": "Test 2",
"name": "Name Test 2"
},
{
"id": "3",
"boat": "Test 3",
"name": "Name Test 3"
},
{
"id": "4",
"boat": "Test 4",
"name": "mller"
}
]
}';
$data = json_decode($json);
//print_r($data);
foreach ($data->teams as $object) {
if ( $object->id == 2) {
echo 'boat is ' . $object->boat . ' and name is ' . $object->name . PHP_EOL;
}
}
And the result of the above example would be
boat is Test 2 and name is Name Test 2

Flatten a Multidimensional Array with key, value and object from a JSON

For 2 days, I'm trying to extract informations from a multidimensional array and I think I'm stuck after trying a lot of things
Here is my json
{
"profile": [
{
"id": "123456",
"hostId": null,
"description": [
{
"id": "name",
"value": "foo"
},
{
"id": "name2",
"value": "foo2"
},
{
"id": "bio",
"value": "heyyyy"
},
{
"id": "location",
"value": "somewhere"
}
],
"ishere": true
}
]
}
I want to manipulate it to have this
{
"id": "123456",
"host": null,
"name": "foo",
"name2": "foo2",
"bio": "heyyyy",
"location": "somewhere",
"ishere": true
}
with this (after a json_decode)
foreach ($array->profileUsers[0]->settings as $item) {
$out2[$item->id] = $item->value;
}
I only have
{
"name": "foo",
"name2": "foo2",
"bio": "heyyyy",
"location": "somewhere"
}
Thank you
This should do the trick:
$obj = json_decode($your_json);
$obj = $obj->profile[0];
foreach($obj->description as $d)
$obj->{$d->id} = $d->value;
unset($obj->description);
$data = json_decode($your_json, true);
$new_array = [];
foreach($data['profile'] as $key=>$item) {
if(is_array($item)) {
$new_array[$item['id']] = $item['value'];
}
else {
$new_array[$key] = $item;
}
}
Hardcoded this, hope it will help.

PHP getting values from nested json

I have this json listed below. I was using json_decode to get some of the values. Such as getting the id value:
$decoded_array = json_decode($result, true);
foreach($decoded_array['issue'] as $issues ){
$value[] = $issues["id"];
This method is working for getting the id value, however, I want to get the emailAddress values for both Bob and John. I believe you can get a single value by doing this:
$value[] = $issues["fields"][people][0][emailAddress];
Is it possible to get both email addresses in an efficient manner?
Edited --------
How would you get data with an expanded dataset? Example:
{
"startAt": 0,
"issue": [
{
"id": "51526",
"fields": {
"people": [
{
"name": "bob",
"emailAddress": "bob#gmail.com",
"displayName": "Bob Smith",
},
{
"name": "john",
"emailAddress": "john#gmail.com",
"displayName": "John Smith",
}
],
"skill": {
"name": "artist",
"id": "1"
}
}
},
{
"id": "2005",
"fields": {
"people": [
{
"name": "jake",
"emailAddress": "jake#gmail.com",
"displayName": "Jake Smith",
},
{
"name": "frank",
"emailAddress": "frank#gmail.com",
"displayName": "Frank Smith",
}
],
"skill": {
"name": "writer",
"id": "2"
}
}
}
]
}
I only want to extract the email addresses from both "fields". Is there an easy way to loop through all the "fields" to get "emailAddress" data?
You need to delve deeper into the array.
foreach ($decoded_array['issue'][0]['fields']['people'] as $person) {
echo $person['emailAddress'];
}

How to create array of nested comments out of flat array from DB

After querying the DB for comments that are nested in a closure table, like Bill Karwin suggests here What is the most efficient/elegant way to parse a flat table into a tree?, I now get the following datastructure from SQL:
"comments": [
{
"id": "1",
"breadcrumbs": "1",
"body": "Bell pepper melon mung."
},
{
"id": "2",
"breadcrumbs": "1,2",
"body": "Pea sprouts green bean."
},
{
"id": "3",
"breadcrumbs": "1,3",
"body": "Komatsuna plantain spinach sorrel."
},
{
"id": "4",
"breadcrumbs": "1,2,4",
"body": "Rock melon grape parsnip."
},
{
"id": "5",
"breadcrumbs": "5",
"body": "Ricebean spring onion grape."
},
{
"id": "6",
"breadcrumbs": "5,6",
"body": "Chestnut kohlrabi parsnip daikon."
}
]
Using PHP I would like to restructure this dataset, so the comments are nested like this:
"comments": [
{
"id": "1",
"breadcrumbs": "1",
"body": "Bell pepper melon mung."
"comments": [
{
"id": "2",
"breadcrumbs": "1,2",
"body": "Pea sprouts green bean."
"comments": [
{
"id": "4",
"breadcrumbs": "1,2,4",
"body": "Rock melon grape parsnip."
}
]
},
{
"id": "3",
"breadcrumbs": "1,3",
"body": "Komatsuna plantain spinach sorrel."
}
]
},
{
"id": "5",
"breadcrumbs": "5",
"body": "Ricebean spring onion grape."
"comments": [
{
"id": "6",
"breadcrumbs": "5,6",
"body": "Chestnut kohlrabi parsnip daikon."
}
]
}
]
I have hacked together a solution, but it seems over complex, and I have a feeling that there is some clever solution out there to do this in an elegant and efficient way, but I dont know how?
Assuming you fetch all your data into an array indexed by the "id":
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$nodes[$row["id"]] = $row;
}
I tested the following and it works to produce the JSON output you want:
foreach ($nodes as &$node) {
$parent = array_shift(array_slice(explode(",",$node["breadcrumbs"]), -2, 1));
if ($parent == $node["id"]) {
$forest["comments"][] = &$node;
} else {
$nodes[$parent]["comments"][] = &$node;
}
}
print json_encode($forest, JSON_PRETTY_PRINT);
I would suggest a 2 stage approach.
Stage 1 : Build an nested array
Stage 2 : Convert array to JSON
Stage 1 can be handled simply by creating your elements based on your breadcrumbs.
For example, for "breadcrumbs": "1,2,4"
$comments_array[1][2][4] = $current_element_from_flat_array;
I'm not sure what the most elegant way to get to the above code is, perhaps by parsing the breadcrumbs into its element and having if-else statements based in this. It might be functional, but It's probably not the most elegant code.
$breadcrumbs_list = explode(",", $pizza);
if (count($breadcrumbs_list) == 2)
$comments_array[$breadcrumbs_list[1]][$breadcrumbs_list[2]] = $current_element_from_flat_array;
else if (count($breadcrumbs_list) == 3)
$comments_array[$breadcrumbs_list[1]][$breadcrumbs_list[2]][$breadcrumbs_list[1]] = $current_element_from_flat_array;
Stage 2 can be done using json_encode() provided by PHP.
$tree = array('NULL' => array('children' => array()));
foreach($array as $item){
if(isset($tree[$item['id']])){
$tree[$item['id']] = array_merge($tree[$item['id']],$item);
} else {
$tree[$item['id']] = $item;
}
$parentid = is_null($item['id_parent']) ? 'NULL' : $item['id_parent'];
if(!isset($tree[$parentid])) $tree[$parentid] = array('children' => array());
//this & is where the magic happens: any alteration to $tree[$item['id']
// will reflect in the item $tree[$parentid]['children'] as they are the same
// variable. For instance, adding a child to $tree[$item['id']]['children]
// will be seen in
// $tree[$parentid]['children'][<whatever index $item['id'] has>]['children]
$tree[$parentid]['children'][] = &$tree[$item['id']];
}
$result = $tree['NULL']['children'];
//always unset references
unset($tree);
This solution needs a little polishing. Hope it helps.

Categories