I have two JSON arrays with some values. I need to merge those values in a format using PHP. Here is the array format and the output format that I needed:
Array 1:
{
"data": {
"1": {
"id": 1,
"name": "red"
},
"25": {
"id": 3,
"name": "green"
}
}
}
Array 2:
{
"data": {
"10": {
"id": 14,
"name": "blue"
},
"22": {
"id": 5,
"name": "white"
}
}
}
Expected Result after merge:
{
"data": {
"1": {
"id": 1,
"name": "red"
},
"25": {
"id": 3,
"name": "green"
}
},
"10": {
"id": 14,
"name": "blue"
},
"22": {
"id": 5,
"name": "white"
}
}
Thank you.
Try this code
<?php
$json1 = '{
"data": {
"1": {
"id": 1,
"name": "red"
},
"25": {
"id": 3,
"name": "green"
}
}
}';
$json2 = '{
"data": {
"10": {
"id": 14,
"name": "blue"
},
"22": {
"id": 5,
"name": "white"
}
}
}';
// Decode json into array
$jArray1 = json_decode($json1, true);
$jArray2 = json_decode($json2, true);
// Merging array
$merge['data'] = $jArray1['data'] + $jArray2['data'];
// Encoding array to json
$mergedJson = json_encode($merge);
print_r( $mergedJson );
?>
$de_json = json_decode('{
"data": {
"1": {
"id": 1,
"name": "red"
},
"25": {
"id": 3,
"name": "green"
}
}}', True);
echo '<pre>';print_r($de_json);
You will get this output
Array
(
[data] => Array
(
[1] => Array
(
[id] => 1
[name] => red
)
[25] => Array
(
[id] => 3
[name] => green
)
)
)
the convert other two json array to php array and
use array_merge() to get the merged array.
Related
I've tried to look up the clue, still not able to solve it though.
I have json like this, and I need it to store in db the following 'id', 'n', 'ct'. But the element "rep" has various numbering. Can anyone help me to create the code "foreach" to be able to call it and then save it?
Basically I need to get result for each "rep" with its "id"
Such as:
rep1 - id 1,2,4,5
rep2 - id 1,2
{ "dataFlags": 8192,
"totalItemsCount": 6,
"indexFrom": 0,
"indexTo": 0,
"items": [{
"rep": {
"1": {
"id": 1,
"n": "volvo",
"ct": "avl_unit_group",
"c": 54071
},
"2": {
"id": 2,
"n": "bmw",
"ct": "avl_unit_group",
"c": 59631
},
"4": {
"id": 4,
"n": "audi",
"ct": "avl_unit_group",
"c": 27264
},
"5": {
"id": 5,
"n": "mercedes",
"ct": "avl_unit",
"c": 18276
}}},
{"rep": {
"1": {
"id": 1,
"n": "tesla",
"ct": "avl_unit",
"c": 24132
},
"2": {
"id": 2,
"n": "scania",
"ct": "avl_unit",
"c": 2178
}},
"repmax": 0
}]}
this code is written in php.
$rep1="";
foreach ($row['item'] as $key => $value) {
$rep1 .=$value->id.'-';
}
$rep1=substr($rep1, 0, -1);
the output will be $rep1= 1-2-4-5
Your JSON data:
$jsonData = '{
"dataFlags": 8192,
"totalItemsCount": 6,
"indexFrom": 0,
"indexTo": 0,
"items": [{
"rep": {
"1": {
"id": 1,
"n": "volvo",
"ct": "avl_unit_group",
"c": 54071
},......
}},
{"rep": {
"1": {
"id": 1,
"n": "tesla",
"ct": "avl_unit",
"c": 24132
},..........
},
"repmax": 0
}]}';
Try below code. it's working. I have used 2 foreach for store your JSON data in the database.
$jsonData = json_decode($jsonData,true);
foreach($jsonData['items'] as $items){
foreach($items['rep'] as $rep){
$sql = "INSERT INTO MyGuests (id, n, ct) VALUES (".$rep['id'].",".$rep['n'].",".$rep['ct'].")";
$conn->query($sql)
}
}
Get result for each "rep" with its "id":
$jsonData = json_decode($jsonData,true);
$allRep = [];
foreach($jsonData['items'] as $items){
$tmpRep = [];
foreach($items['rep'] as $key => $rep){
$tmpRep [] = $key;
}
$allRep[] = implode(', ',$tmpRep);
}
echo "<pre>";
print_r($allRep);
Output:
Array
(
[0] => 1, 2, 4, 5
[1] => 1, 2
)
Check this:
$arr = json_decode($yourJSONstring);
foreach($arr->items as $index=>$rep){
foreach($rep->rep as $element){
$reps[$index][] = $element->id;
}
}
Reps array will look like:
Array (
[0] => Array ( [0] => 1 [1] => 2 [2] => 4 [3] => 5 )
[1] => Array ( [0] => 1 [1] => 2 )
)
So you can easily convert it to string format as you desire.
Well, I have a web project and I have to be saving things temporarily, I started work with a json file, so far I can add and update.
The json file looks like this:
[
{
"username": "Baldwin",
"products": [
{
"id": 0,
"amount": 10
},
{
"id": 1,
"amount": 9
},
{
"id": 2,
"amount": 9
}
]
},
{
"username": "Alice",
"products": [
{
"id": 0,
"amount": 11
},
{
"id": 1,
"amount": 13
},
{
"id": 2,
"amount": 6
}
]
},
{
"username": "Terry",
"products": [
{
"id": 0,
"amount": 12
},
{
"id": 1,
"amount": 14
},
{
"id": 2,
"amount": 5
}
]
}
]
The problem comes when I want to delete an specific array or when I want to delete it completely, I can do it and it works fine, but I have the doubt about why when I delete the object, other fields are add to the json file, like an id.
When i delete just one product inside of the "products" array something like this happen:
[
{
"username": "Baldwin",
"products": { "1": { "id": 1, "amount": 9 }, "2": { "id": 2, "amount": 9 } }
},
{
"username": "Alice",
"products": [
{ "id": 0, "amount": 11 },
{ "id": 1, "amount": 13 },
{ "id": 2, "amount": 6 }
]
},
{
"username": "Terry",
"products": [
{ "id": 0, "amount": 12 },
{ "id": 1, "amount": 14 },
{ "id": 2, "amount": 5 }
]
}
]
And when i delete a complete array from the json file, something like this happen:
{
"1": {
"username": "Alice",
"products": [
{ "id": 0, "amount": 11 },
{ "id": 1, "amount": 13 },
{ "id": 2, "amount": 6 }
]
},
"2": {
"username": "Terry",
"products": [
{ "id": 0, "amount": 12 },
{ "id": 1, "amount": 14 },
{ "id": 2, "amount": 5 }
]
}
}
My php file to delete:
<?php
// load file
$data = file_get_contents('results.json');
// decode json to associative array
$json_arr = json_decode($data, true);
$flag = false;
// We check if the user wants to delete all or just one product
if(isset($_POST["all"])):
$username = $_POST["username"];
foreach ($json_arr as $key => $value):
// find the username on the json file
if($value["username"] == $username):
unset($json_arr[$key]);
break;
endif;
endforeach;
elseif(isset($_POST["one"])):
$username = $_POST["username"];
$id = $_POST["id"];
foreach ($json_arr as $key => $value):
// find the username on the json file
if($value["username"] == $username):
// loop products of the current username
foreach ($json_arr[$key]["products"] as $k => $product):
// find the id of the product
if($json_arr[$key]["products"][$k]["id"] == (int)$id):
// delete the product
unset($json_arr[$key]["products"][$k]);
endif;
endforeach;
endif;
endforeach;
endif;
// encode json and save to file
file_put_contents('results.json', json_encode($json_arr));
// redirect to show.php
header("Location: show.php");
?>
I've been taking a look to questions like this one but i couldn't find something with php, i would like to know how to solve this or if this is normal.
What happens when you use unset($json_arr[0]) is that the first element is removed, but the keys are not updated. If you inspect the array after the removal, you'll find that your array has two elements, at $json_arr[1] and $json_arr[2].
When you then perform a json_encode($json_arr) on this, PHP's JSON decoder looks at the array and since arrays are supposed to begin at the 0th element but this array begins at 1, it decides that in order to preserve the keys, the array would have to be converted to an associative array - which transforms the integer array keys into string keys in JSON.
For a short and quick solution, you can try:
$json_arr = array_diff($json_arr, [$key]);
You could even use array_splice or array_values - see here for inspiration.
I use json_decode Php function to get a JSON array of countries datas.
{
"Countries":
[
{
"Code": "AD",
"Name": "Andorre"
},
{
"Code": "AE",
"Name": "Émirats Arabes Unis"
},
{
"Code": "AF",
"Name": "Afghanistan"
},
{
"Code": "AG",
"Name": "Antigua-Et-Barbuda"
},
If I want to retrieve the Code of the 1st element I can do:
$result = json_decode($sXML);
$final = $result->Countries[0]->Name;
And $final will have the value of 'Andorre'.
But what if I want to retrieve the same value 'Andorre' using its correspoding Code ?
Is it possible to do it ?
I know there is an option for the json_function() to obtain an associative array instead of a JSON array, but how would you use it to get the value 'Andorre' using its Code ?
Thank you
<?php
$s = '{
"Countries":
[
{
"Code": "AD",
"Name": "Andorre"
},
{
"Code": "AE",
"Name": "Émirats Arabes Unis"
},
{
"Code": "AF",
"Name": "Afghanistan"
},
{
"Code": "AG",
"Name": "Antigua-Et-Barbuda"
}
]
}';
$arr = json_decode($s, true);
print_r(array_column($arr['Countries'], "Name", "Code"));
?>
yields
Array
(
[AD] => Andorre
[AE] => Émirats Arabes Unis
[AF] => Afghanistan
[AG] => Antigua-Et-Barbuda
)
Here we are using two function for achieving this array_column and array_combine to retrieve the expected output.
Try this code snippet here
<?php
ini_set('display_errors', 1);
$string='{
"Countries":
[
{
"Code": "AD",
"Name": "Andorre"
},
{
"Code": "AE",
"Name": "Émirats Arabes Unis"
},
{
"Code": "AF",
"Name": "Afghanistan"
},
{
"Code": "AG",
"Name": "Antigua-Et-Barbuda"
}
]
}';
$array=json_decode($string,true);
$codes= array_column($array["Countries"], "Code");//Retrieving column code
$names= array_column($array["Countries"], "Name");//Retrieving column name
$data= array_combine($codes, $names); //combining array with code as keys and names as values.
print_r($data);`
Output:
Array
(
[AD] => Andorre
[AE] => Émirats Arabes Unis
[AF] => Afghanistan
[AG] => Antigua-Et-Barbuda
)
I guess you can use something like:
function search_json($obj, $field, $value) {
foreach($obj as $item) {
foreach($item as $child) {
if(isset($child->$field) && $child->$field == $value) {
return $child->Name;
}
}
}
return null;
}
print_r(search_json($result, "Code", "AD"));
# Andorre
I 'm trying to make some pages with php and curl using REST API. I can connect application and get all values as JSON format with curl on PHP. But, I can not parse values what i want.
I used this PHP commands for decode json values ;
$data = json_decode($response, true);
print_r($data);
When I use this command i'm getting returning value like this ;
Array ( [links] => Array ( ) [content] => Array ( [0] => Array (
[#type] => ConsumerEnt [links] => Array ( [0] =>
Array ( [#type] => link [rel] => GET: Request [href] =>
http.....
) => Array ...etc
There are arrays inside arrays.. I could not find how to parse values i want. You can see values i want at following json codes;
Do you have any idea how it can be possible ?
Than
You can see Decoded JSON by http://json.parser.online.fr/
{
"links": [],
"content": [
{
"#type": "ConsumerEnt",
"links": [
{
"#type": "link",
"rel": "GET: Request",
"href": "https://ip/url"
},
{
"#type": "link",
"rel": "POST:Request",
"href": "https://ip/url"
}
],
"entitledOrg": [
{
"tRef": "local",
"tLabel": "local",
"sRef": "768882f2-cf89-4cc8-92b7",
"sLabel": "USsB01"
}
],
"citems": "a0221dfd-00f9-4019-95ed",
"name": "NAME I WANT TO GET",
"description": "Basic",
"isNoteworthy": false,
"dateCreated": "2016-09-25T11:44:02.698Z",
"lastUpdatedDate": "2016-09-25T12:46:45.474Z",
"iconId": "a0221dfd-00f9-4019-95ed-a74faeb2e1b2",
"catalogItemTypeRef": {
"id": "com.company",
"label": "Compo"
},
"serviceRef": {
"id": "7c92b9a5-9dd5-4819-9320-4127b1e3009d",
"label": "NAME I WANT TO GET"
},
"outputResourceRef": {
"id": "composition.type",
"label": "test"
}
},
{
"#type": "ConsumerEnti",
"links": [
{
"#type": "link",
"rel": "GET: Request",
"href": "https://ip/url"
},
{
"#type": "link",
"rel": "POST:Request",
"href": "https://ip/url"
}
],
"entitledOrg": [
{
"tRef": "local",
"tLabel": "local",
"sRef": "768882f2-cf89-4cc8-92b7",
"sLabel": "astDF1"
}
],
"catalogItemId": "89b43bcb-4b23-4fc0-af26-66bd5c6bd1bc",
"name": "NAME I WANT TO GET",
"description": "RASDhFASel",
"isNoteworthy": false,
"dateCreated": "2016-10-27T07:55:03.243Z",
"lastUpdatedDate": "2016-10-27T07:56:00.754Z",
"iconId": "compos.png",
"catalogItemTypeRef": {
"id": "com.company",
"label": "Compo"
},
"serviceRef": {
"id": "7c92b9a5-9dd5-4819-9320-4127b1e3009d",
"label": "NAME I WANT TO GET"
},
"outputResourceRef": {
"id": "composition",
"label": "Dep"
}
}
],
"metadata": {
"size": 20,
"totalElements": 2,
"totalPages": 1,
"number": 1,
"offset": 0
}
}
I guess i solved my issue like this ;
$data = json_decode($response, true);
print_r($data);
$j=count($data["content"]);
for ( $say=0 ; $say < $j ; $say++ )
{
print $data["content"][$say]["name"];
}
as a result i can list my products ;
Product1
Product2
Product3
How would I merge both JSON arrays and then sort the value of ID so that the result displays the highest number to the lowest number?
For example, my desired output from the script below would be:
1 - Jimbo
2 - Bob
6 - Luke
12 - Chris
16 - Jonas
36 - Sam
Here's my JSON arrays:
$json1 ='
{
"error": "trueee",
"info": {
"collections": [{
"ID": "1"
"Name": "Jimbo"
}, {
"ID": "36"
"Name": "Sam"
}, {
"ID": "2",
"Name": "Bob"
}]
}
}
';
$json2 ='
{
"error": "trueee",
"info": {
"collections": [{
"ID": "12"
"Name": "Chris"
}, {
"ID": "6"
"Name": "Luke"
}, {
"ID": "16"
"Name": "Jonas"
}]
}
}
';
You need to merge the arrays from the json string. First json decode for getting the arr with associative array than get the columns of ID using array_column, after that you need to merge the two array and finally sort them.
Online Check and a Long Conversation
$json1 ='
{
"error": "trueee",
"info": {
"collections": [{
"ID": "1"
}, {
"ID": "36"
}, {
"ID": "2"
}]
}
}
';
$json2 ='
{
"error": "trueee",
"info": {
"collections": [{
"ID": "12"
}, {
"ID": "6"
}, {
"ID": "16"
}]
}
}
';
$arr1 = json_decode($json1, true);
$arr2 = json_decode($json2, true);
$arr1 = array_column($arr1['info']['collections'], "ID");
$arr2 = array_column($arr2['info']['collections'], "ID");
$arr = array_merge($arr1, $arr2);
sort($arr);
echo '<pre>';
print_r($arr);
Result:
Array
(
[0] => 1
[1] => 2
[2] => 6
[3] => 12
[4] => 16
[5] => 36
)