Get values from multidimensional array | JSON - mysql

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;
}

Related

Selecting Data from JSON via PHP

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];

Encoding an array of hashes in Perl

I'm trying to do something that seems to be very simple, but I can't figure out how to do it in Perl : I want to output a JSON-formatted array of hashes.
The array of hashes in question is actually an array of DBIx::MyParse Items object instances. Here is my code :
use strict;
use DBIx::MyParse;
use JSON::PP;
my $json = JSON::PP->new->ascii->pretty->allow_nonref;
our $parser = DBIx::MyParse->new( database => "test", datadir => "/tmp/myparse" );
our $query = $parser->parse("UPDATE table1 SET field1 = 1;");
$json->convert_blessed(1);
print $json->encode(#{$query} );
And this is what this script outputs :
"SQLCOM_UPDATE"
Which is actually the first element of the array that I want to output as a whole. Here is the content of the array that I see when I step-by-step debug the script :
I would like to have the whole structure in my JSON output. How can I achieve this ?
JSON::encode just expects a single argument, not a list. Use $json->encode( $query ).

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?

apply different functions to each element of a Perl data structure

Given an arbitrarily nested data structure, how can I create a new data structure so that all the elements in it have been standardized by applying a function on all the elements depending on the type of the element. For example, I might have
$data = {
name => 'some one',
date => '2010-10-10 12:23:45',
sale => [34, 22, 65],
cust => {
name => 'Jimmy',
addr => '1 Foobar Way',
amnt => 452.024,
item => ['books', 'pens', 'post-it notes']
}
}
and I want to convert all text values to upper case, all dates to UTC date times, find the square of all integers, round down all real numbers and add 1, and so on. So, in effect, I want to apply a different function to each element depending on the type of element.
In reality the data might arrive via a database query, in which case they are already a Perl data structure, or they might start life as a JSON object, in which case I can use JSON::from_json to convert it to a Perl data structure. The idea is to standardize all the values in the data structure based on the value type, and then spit out the Perl data structure back again as a JSON object.
I read the answers to executing a function on every element of a data structure and feel that Data::Rmap might do the trick, but can't figure out how. Seems like Rmap works on all the keys as well, not just the values.
It's crazy straightforward with Data::Rmap you mentioned.
use Data::Rmap qw( rmap );
rmap { $_ = transform($_); } $data;
Regarding the question in the comments:
use Data::Rmap qw( rmap );
use Scalar::Util qw( looks_like_number );
# Transforms $_ in place.
sub transform {
if (looks_like_number($_)) {
if (...) {
$_ *= 2;
}
$_ = 0+$_; # Makes it look like a number to JSON::XS
} else {
...
}
}
&rmap(\&transform, $data);

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]