Selecting Data from JSON via PHP - json

I have json data and i want to select some data plese read the json
"response":{"status":1,"httpStatus":200,"data":{"page":1,"current":0,"count":982,"pageCount":1,
"data":{"1131":{"OfferFile":
{"offer_id":"547"}},
"1525":{"OfferFile":{"offer_id":"717"}}
}
From above data i want to select 1131 and 1525 integers via php
Please give me a code snd thanks.

I am assuming that the actual JSON that you have, when formatted properly, looks as follows:
{
"status":1,
"httpStatus":200,
"page":1,
"current":0,
"count":982,
"pageCount":1,
"data":{
"1131":{
"OfferFile":{
"offer_id":"547"
}
},
"1525":{
"OfferFile":{
"offer_id":"717"
}
}
}
}
If so, you would get the integers with the following code:
$json = json_decode($string, true);
$ids = array_keys($json['data']);

Use json_decode to parse your :
$json = json_decode('{..your data..}', true);
$data = $json['data']['data'];
The $data variable is an array. To get "1131" and "1525", you need to get array_keys of $data via :
$vals = array_keys($data);
$1131 = $vals[0];
$1525 = $vals[1];

Related

Get values from multidimensional array | JSON

I am trying to access the values of this array in PHP. It's a multidimensional array.
I need to get values from the array and insert it in the DB.
Inserting is the second part of the problem. First parts is getting the values from it.
JSON -
{
"itempicture":[
{
"status":"3"
},
{
"ItemCode":"001",
"ItemImage":"image1",
"ItemCategory":"shirt",
"ShowOnPOS":"Yes",
"LastModifiedOn":"2018-06-02 11:53:57"
},
{
"ItemCode":"002",
"ItemImage":"image2",
"ItemCategory":"shirt",
"ShowOnPOS":"Yes",
"LastModifiedOn":"2018-06-02 11:53:57"
}]}
Here the "itempicture" is the table name and all the keys, i.e 'itemcode', 'itemimage, etc are the SQL columns'".
I need to get the values of the SQL columns and insert it into the DB.
So far i have tried this -
$data = file_get_contents($url);
$json_array = (array)(json_decode($data));
print_r($json_array);
foreach($user->itempicture as $mydata)
{
echo $mydata->itempicture . "\n";
foreach($mydata->itempicture as $values)
{
echo $values->itempicture . "\n";
}
}
Using MYSQL in Object-oriented method to insert it in DB, with a simple query like "INSERT INTO table_name
VALUES (value1, value2, value3, ...)"
So table name will be the "itempicture" present in the array and values will be the values of the keys in the array.
This may be of help. Instead of looping through the properties with a foreach and printing, you'll want to use them to build an array to use as parameters for a prepared query, or build the query directly. But this shows you how to access those properties -
<?php
$j='{
"itempicture":[
{
"status":"3"
},
{
"ItemCode":"001",
"ItemImage":"image1",
"ItemCategory":"shirt",
"ShowOnPOS":"Yes",
"LastModifiedOn":"2018-06-02 11:53:57"
},
{
"ItemCode":"002",
"ItemImage":"image2",
"ItemCategory":"shirt",
"ShowOnPOS":"Yes",
"LastModifiedOn":"2018-06-02 11:53:57"
}]}';
$jo=json_decode($j);
print("status ".$jo->itempicture[0]->status."\n");
for($i=1;$i<count($jo->itempicture);$i++){
foreach($jo->itempicture[$i] as $prop=>$val){
print($prop." = ".$val."\n");
}
}
?>
There are some issues I have seen in your code:
You cast the result of json_decode($data) to an array, an then later you try to use property-access to access the "itempicture" property. I have removed this cast.
In the first foreach use the variable $user, I guess you meant to use $json_array.
The inner loop is not really used, you can access the properties directly
After having fixed this issues the code looks like that and works with your given JSON. I have just echo-ed the values since you have not told us which DB-abstraction you use, but you can use the values to populate the database.
$data = file_get_contents($url);
$json_array = (json_decode($data));
print_r($json_array);
foreach($json_array->itempicture as $mydata)
{
if (!property_exists($mydata, 'ItemCode')) {
// Ignore entries which are invalid (have no ItemCode property)
continue;
}
echo implode(' - ', [
$mydata->ItemCode,
$mydata->ItemImage,
$mydata->ItemCategory,
$mydata->ShowOnPOS,
$mydata->LastModifiedOn,
]), PHP_EOL;
}

Database json column returning escaped string in laravel blade

I have saved some Json data in a MySQL column. While fetching the data to a Laravel Blade application the json fields are all escaped. Hence, I am facing issues while reading the json data.
[
{
"id": "1",
"json_backup": "{\"id\":\"2\",\"organization_id\":\"1\",\"amount\":\"7800.00\",\"date\":\"2015-05-11\",\"created_at\":\"2015-05-11 07:20:45\",\"updated_at\":\"2015-05-11 07:20:45\"}",
"ip": "127.0.0.1",
"created_at": "2015-05-12 12:21:16",
"updated_at": "2015-05-12 12:21:16"
}
]
The json_backup field in the above example is escaped. How do I ensure that this field is not escaped.
Code to fetch the data
$activity = Activity::find(1);
In the View:
#foreach ($activities AS $activity)
#foreach($activity->json_backup AS $order)
#endforeach
#endforeach
Error:
Invalid argument supplied for foreach()
Any help would be much appreciated.
#saaz When you are storing the JSON in MySQL, use
json_encode($json_backup, JSON_UNESCAPED_SLASHES)
HTH
This error is coming on the second foreach section.
Please try it in somewhat this way.
$json = json_decode($activity->json_backup, true);
This would work but can't say it definitely. And even if you have problem refactor the code and create a class with following code:
function escapeJsonString($value) {
$escapers = array("\\", "/", "\"", "\n", "\r", "\t", "\x08", "\x0c");
$replacements = array("\\\\", "\\/", "\\\"", "\\n", "\\r", "\\t", "\\f", "\\b");
$result = str_replace($escapers, $replacements, $value);
return $result;
}
And simply say
$json = escapeJsonString($activity->json_backup);
This one would definitely work. Hope so this helps.

merging json objects in php

how can i merge two json objects in php
one of array is like this
$arr_data = array('id'=>$country_id);
$arr = json_encode($arr_data);
and another one is like this:
$arr_places = json_encode($xmlDoc);
now I want to merge them into a single json object. How can I do this.
It depends very much on what you mean by "merge". Just a plain merge or you will need to eliminate the duplicated attributes?...etc.
The simplest way is just like what xdazz mentioned.
So you should merge the array first and then use json_encode.
$json = json_encode(array_merge($arr_data, $xmlDoc));
Merge the results and then encode.
$arr_data = array('id'=>$country_id);
$res = array_merge( $arr_data, $xmlDoc );
$merged = json_encode($res);
Most of the answers here assume that this is a case where one is confronted with two arrays, rather than objects. OP was asking about merging two objects into a single JSON.
While there are many solutions to this, I've got a hack that goes a step further and actually merges the objects into a single JSON string by converting the objects to JSON strings, then back to associative arrays, and then back to JSON.
Could be an efficiency fail, but does the job :-) Here's a code sample:
/**
* Merges two objects into a single JSON structure
* #param object $obj1
* #param object $obj2
* #return string the resuling JSON string
*/
function mergeToJSON($obj1, $obj2) {
$json1 = json_encode($obj1);
$json2 = json_encode($obj2);
if ($json1 === FALSE OR $json2 === FALSE) {
return "";
}
$array1 = json_decode($json1, TRUE);
$array2 = json_decode($json2, TRUE);
$data = array_merge($array1, $array2);
return json_encode($data);
}
The above mentioned solution is not working for me with PHP version 5.5.12
What I want to is in short append to json strings and form one json string out of it, as explained below:
$str1 = {
timestamp: "2015-04-03T08:08:51+00:00",
user: "admin",
src_ip: "127.0.0.1"
}
$str2 = {
timestamp: "2015-04-03T08:08:51+00:00",
user: "Peter_x",
src_ip: "127.0.0.1"
}
$value1 = json_decode ($str1, TRUE);
$value2 = json_decode ($str2, TRUE);
$combined = array_merge ($value1, $value2);
$combined_json = json_encode ($combined);
file_put_contents("c:\outputfile", $combined_json, FILE_APPEND);
The result is:
{
"timestamp": "2015-04-03T08:08:51+00:00",
"user": "admin",
"src_ip": "127.0.0.1",
}
{
"timestamp": "2015-04-03T08:08:51+00:00",
"user": "Peter_x",
"src_ip": "127.0.0.1",
}
Instead I expect one single json string. Firefox fails to parse it. What surprises me is that in the resulting string the keys are within quotes. (e.g: "timestamp").
Can any one tell me what is wrong with the code or how to join the two json strings to one?

Perl to JSON, with key/value pairs

I am trying to output some data from Perl to JSON. I can do a simple output, but would like to structure it better.
I have an array with an id, a start time and an end time. This is the code I am using to output:
print header('application/json');
my $json->{$entry} = \#array;
my $json_text = to_json($json);
print $json_text;
Which returns:
{"Season":[["1","1330065300","1344038401"],["7","1298505601","1312416001"]]}
But I would like to output something more like:
{"Season":0[{"id":1,"DateStart":1330065300,"DateEnd":1344038401},{"id":7,"DateStart":1298505601,"DateEnd":1312416001}]}
Can anyone help on how to better structure my output?
---UPDATE------
Thanks Michael. I have tried to implement your example.
This is the code at the moment:
foreach my $key (keys %$seasons)
{
$seasons->{$key} =
[
map
{
{ id=>$_[0], DateStart=>$_[1], DateEnd=>$_[2] }
} #{$seasons->{$key}}
];
}
But it returns the error (referring to the foreach line):
Not a HASH reference at line 148
$seasons is an arrayref return from a SQL fetchall_arrayref
Any clues?
You basically want to convert an array of arrays to an array of hashes, and you can do this using map. Assuming $data is your structure, this should do it:
for my $key (keys %$data) {
$data->{$key} = [
map {
{ id => $_->[0], DateStart => $_->[1], DateEnd => $_->[2] }
} #{$data->{$key}}
];
}
If you want to output an array of objects with key/value pairs instead of an array of arrays, then put appropriate data into to_json in the first place.
i.e. an array of hashrefs and not an array of arrayrefs.
You can use map to transform the data.
Whenever you're trying something like this, always check CPAN to see if someone has done it before and not try to reinvent the wheel. I found a module called JSON that seems to do exactly what you want.
There's an example on that page that does exactly what you want. Here's a quick paraphrase:
use JSON; # imports encode_json, decode_json, to_json and from_json.
# simple and fast interfaces (expect/generate UTF-8)
my $utf8_encoded_json_text = encode_json \#array;
Can't get easier than that. The best part is that this will work no matter how complex your array structure gets.

Data column(s) for axis #0 cannot be of type string error in google chart

I tried to populate google chart datatable in server side using PHP.I got JSON file properply, but the Chart not display in client Application. I got error-Data column(s) for axis #0 cannot be of type string . My coding is below here.
After fetching data from database,
$colarray=array(array("id"=>"","label"=>"userid","pattern"=>"","type"=>"number"),array("id"=>"","label"=>"name","pattern"=>"","type"=>"string"));
$final=array();
for($i=0;$i<$rows;$i++)
{
$id[$i]=pg_fetch_result($res1,$i,'id');
$name[$i]=pg_fetch_result($res1,$i,'name');
$prefinal[$i]=array("c"=>array(array("v"=>$name[$i]),array("v"=>$name[$i])));
array_push($final,$prefinal[$i]);
}
$table['cols']=$colarray;
$table['rows']=$final;
echo json_encode($table);
My Output Json:
{
"cols":[
{"id":"","label":"userid","pattern":"","type":"number"},
{"id":"","label":"name","pattern":"","type":"string"}
],
"rows":[
{"c":[{"v":"101"},{"v":"Aircel"}]},
{"c":[{"v":"102"},{"v":"Srini"}]},
{"c":[{"v":"103"},{"v":"Tamil"}]},
{"c":[{"v":"104"},{"v":"Thiyagu"}]},
{"c":[{"v":"105"},{"v":"Vasan"}]},
{"c":[{"v":"107"},{"v":"Senthil"}]},
{"c":[{"v":"108"},{"v":"Sri"}]},
{"c":[{"v":"109"},{"v":"Docomo"}]},
{"c":[{"v":"106"},{"v":"Innodea"}]}
]
}
How to solve this issue?
To extend on #sajal's accurate answer: Change the last line of your code from:
echo json_encode($table);
to:
echo json_encode($table, JSON_NUMERIC_CHECK);
This will tell json_encode to recognize numbers and abstain from wrapping them in quotes (Available since PHP 5.3.3.).
http://php.net/manual/en/json.constants.php#constant.json-numeric-check
You specify type of userid as number... but pass string.. thats causing the problem.
I just wasted 30 mins with the opposite problem ...
Your output json should look like :-
{
"cols":[
{"id":"","label":"userid","pattern":"","type":"number"},
{"id":"","label":"name","pattern":"","type":"string"}
],
"rows":[
{"c":[{"v":101},{"v":"Aircel"}]},
{"c":[{"v":102},{"v":"Srini"}]},
{"c":[{"v":103},{"v":"Tamil"}]},
{"c":[{"v":104},{"v":"Thiyagu"}]},
{"c":[{"v":105},{"v":"Vasan"}]},
{"c":[{"v":107},{"v":"Senthil"}]},
{"c":[{"v":108},{"v":"Sri"}]},
{"c":[{"v":109},{"v":"Docomo"}]},
{"c":[{"v":106},{"v":"Innodea"}]}
]
}
On a BarChart, one of the columns (the second one) has to be a number. That can cause this error message.
In your drawChart() function, you are probably using google.visualization.arrayToDataTable, and this does not allow any nulls. Please use addColumn function explicitly
If the Data format should be like:
data: [
["string", "string"], //first Column
["string1", number],
["string2", number],
["string3", number],
]
then you can overcome this error.
when you are passing your data from controller you need to do like so: just take an example I have controller and I am sending data through it via group by.
controller:
\DB::statement("SET SQL_MODE=''");//this is the trick use it just before your query
$Rspatients = DB::table('reports')
->select(
DB::raw("day(created_at) as day"),
DB::raw("Count(*) as total_patients"))
->orderBy("created_at")
->groupBy(DB::raw("day(created_at)"))
->get();
$result_patients[] = ['day','Patients'];
foreach ($Rspatients as $key => $value) {
$result_patients[++$key] = [$value->day,$value->total_patients];
}
return view('Dashboard.index')
->with('result_patients',json_encode($result_patients,JSON_NUMERIC_CHECK));
if there is no JSON_NUMERIC_CHECK, so the data will be array of strings while if there is json check the data will be converted to array of numbers.
before JSON check data:
4: (2) ["24", "413"]
5: (2) ["25", "398"]
After JSON Check data:
4: (2) [24, 413]
5: (2) [25, 398]