in array, json data and put in MySql with php - arrays

I have a data under format 'JSON' like this one :
{
"email": "john#john.fr",
"line_items": [
{
"sku": "123456789",
"price": "0.67",
"price_with_tax": "4.00",
"tax_lines": [
{
"title": "tax010",
"rate": 0.01,
"price": "1.11"
},
{
"title": "tax00200",
"rate": 0.02,
"price": "2.22"
}
]
},
{
"sku": "012345666",
"price": "1.67",
"price_with_tax": "5.00",
"tax_lines": [
{
"title": "tax0003000",
"rate": 0.03,
"price": "3.33"
}
]
}
]
}
I want put it in my database (MySql) by PDO::prepare. My following sql query works but second line_items have not good value im Mysql :
1st item :::: good value
email:john#john.fr
sku:123456789
price:0.67
price_with_tax:4.00
price_tax1:1.11
price_tax2:2.22
2nd item ::::
email:john#john.fr
sku:012345666
price:1.67
price_with_tax:5.00
wrong value ::::
price_tax1:1.11
price_tax2:2.22
How can I put it good value ?
here is my code :
$dataDecode = json_decode($jsondata);
$email = $dataDecode->email;
try
{
$dtbs = new PDO($dsn_dev, $pdo_user, $pdo_password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
}
catch (Exception $e)
{
die('Error : ' . $e->getMessage());
}
try
{
foreach ($dataDecode->line_items as $obj)
{
$var_sku = $obj->sku;
$var_price = $obj->price;
$var_price_with_tax = $obj->price_with_tax;
$taxNewArray = array();
foreach ($dataDecode->line_items[0]->tax_lines as $obj2)
{
array_push($taxNewArray , $obj2);
}
$val1st = array_shift($taxNewArray);
$val2nd = array_pop ($taxNewArray);
$var_tax1 = $val1st->price;
$var_tax2 = $val2nd->price;
$stmt = $dtbs->prepare("INSERT INTO $tabledata ($mysql_email, $mysql_sku, $mysq_price, $mysql_price_with_tax, $mysql_price__tax1___line_items, $mysql_price__tax2___line_items)
VALUES (:email, :sku, :price, :price_with_tax, :price_tax1, :price_tax2)");
$stmt->execute(array(':email'=>$email,
':sku'=>$var_sku,
':price'=>$var_price,
':price_with_tax'=>$var_price_with_tax,
':price_tax1'=>$var_tax1,
':price_tax2'=>$var_tax2
));
}
}
catch(Exception $e)
{
throw $e;
}
Do you have a idée ?

If there's only one entry in tax_lines, your code will try to set $var_tax2 from the nonexistent second entry. You need to check for this and substitute some other value:
$var_tax2 = $val2nd ? $val2nd->price : '0.0';
The other problem is this line:
foreach ($dataDecode->line_items[0]->tax_lines as $obj2)
You're using the tax lines from the first line item every time. That should be:
foreach ($obj->tax_lines as $obj2)

Related

Loop through snowflake array with object_insert

I have JSON data in snowflake table as follows
{
"audit": "ss",
"gdapi": "ww",
"lock": "aa",
"messageBody": {
"id": 111,
"policycontainer": {
"policyTerms": [
{
"Billing": {
"checkpayment": {
"bankroutingnumber": "value1"
}
}
},
{
"Billing": {
"checkpayment": {
"bankroutingnumber": "value2"
}
}
}
]
}
}
}
I want to change the value of bankroutingnumber to null for that I've written the following query
update test
set RECORD_CONTENT =
object_insert(RECORD_CONTENT, 'messageBody',
object_insert(parse_json(RECORD_CONTENT:messageBody), 'policycontainer',
object_insert(parse_json(RECORD_CONTENT:messageBody):policycontainer, 'policyTerms',
object_insert(parse_json(RECORD_CONTENT:messageBody):policycontainer:policyTerms[0], 'Billing',
object_insert(parse_json(RECORD_CONTENT:messageBody):policycontainer:policyTerms[0]:Billing, 'checkpayment',
object_insert(parse_json(RECORD_CONTENT:messageBody):policycontainer:policyTerms[0]:Billing:checkpayment,'bankroutingnumber','null',true), true),true), true), true),true)
After running this the result looks like follow
{
"audit": "ss",
"gdapi": "ww",
"lock": "aa",
"messageBody": {
"id": 111,
"policycontainer": {
"policyTerms": {
"Billing": {
"checkpayment": {
"bankroutingnumber": "null"
}
}
}
}
}
}
now the array is gone. I want to keep the array and loop through policyTerms and edit all bankroutingnumber to null
In this case, you may use LATERAL FLATTEN for "RECORD_CONTENT:messageBody.policycontainer.policyTerms" and then OBJECT_AGG to make them one value again, and update the column but I think you could just use a simple regexp_replace for a "faster" query:
select parse_json( regexp_replace( RECORD_CONTENT::STRING, '"bankroutingnumber":"[^"]*"','"bankroutingnumber":"null"')) from test;
update version:
update test
set RECORD_CONTENT = parse_json( regexp_replace( RECORD_CONTENT::STRING, '"bankroutingnumber":"[^"]*"','"bankroutingnumber":"null"'));

Remove duplicates from different JSON Arrays

I have a JSON structure that has a lot of arrays.I want to check if there are duplicates.Not inside the same array but in different arrays.Also i want the other fields to stay as is.
Here is an example of my structure:
{
"Collection":[
{
"field0":"string",
"field1":"string",
"field2":"string",
"field3":"string",
"field4":"string",
"field5":"string",
"field6":"string",
"field7":"string",
"field8":"string",
"field9":[
"test1"
"test2"
"test3"
]
},
{
"field0":"string",
"field1":"string",
"field2":"string",
"field3":"string",
"field4":"string",
"field5":"string",
"field6":"string",
"field7":"string",
"field8":"string",
"field9":[
"test8"
"test2"
"test9"
]
}
]
}
And here is what I expect:
{
"Collection":[
{
"field0":"string",
"field1":"string",
"field2":"string",
"field3":"string",
"field4":"string",
"field5":"string",
"field6":"string",
"field7":"string",
"field8":"string",
"field9":[
"test1"
"test2"
"test3"
]
},
{
"field0":"string",
"field1":"string",
"field2":"string",
"field3":"string",
"field4":"string",
"field5":"string",
"field6":"string",
"field7":"string",
"field8":"string",
"field9":[
"test8"
"test9"
]
}
]
}
I don't know if this is relevant but this is a firestore collection.
O'k, I don't know Swift, but I can show you how to do it:
<?php
$json = <<<JSON
{
"Collection":[
{
"field1":[
"test1",
"test2",
"test3"
]
},
{
"field2":[
"test8",
"test2",
"test9"
]
}
]
}
JSON;
$entities = json_decode($json, true); // Decode JSON
$collection = $entities['Collection']; // Grab array of fields inside collection
$elements = []; // Initialize an empty array of unique elements
$result = [];
foreach ($collection as $index => $fieldObject) {
$fieldName = array_keys($fieldObject)[0]; // Get field name
// Get value from array of values of this field
foreach ($fieldObject[$fieldName] as $valueKey => $value) {
// Check if your value is not in array of unique elements
if (!in_array($value, $elements)) {
$elements[] = $value; // Add value if is not
// Add value to your new array
$result['Collection'][$index][$fieldName][] = $fieldObject[$fieldName][$valueKey];
}
}
}
$result = json_encode($result); // Encode it back to JSON
Here is the working example in sandbox: http://sandbox.onlinephpfunctions.com/code/a78cff49cc31c15e7e1373f7e1f66b7951f129e9

How best to Compare JSON object values to a fixed array in JScript

I would like to compare JSON values to an array of values but I d'ont know what's the best scenario to go with.
I got a JSON object with expected values (could have 1 value , 2 or more)
I have a DB function that returns a fix number of values, say 10 values all the time and I would like to know if my JSON values matches the right one coming from DB.
Ex:
My JSON var is :
var expValues = {
"id": "123",
"age": 23
};
My DB will push some values to an Array of objects.
Ex:
if ((rs.BOF) && (rs.EOF))
{
//nothing found;
}
else
{
while (!rs.EOF)
{
aDetails.push(
{
"id": rs.fields("id").Value,
"name": rs.fields("name").Value,
"age": rs.fields("age").Value,
"sex": rs.fields("sex").Value,
"hobby": rs.fields("hobby").Value
});
rs.MoveNext();
}
}
rs.close;
//Close connection then return
return aDetails;
basically I want to make sure values coming from JSON match the right ones coming from DB. (id for example).
I have assumed aDetails to have something like below data.
let aDetails = [{
"id": "123",
"name": "as",
"age": 23,
"sex": "m",
"hobby": "abc"
}, {
"id": "1234",
"name": "as1",
"age": 23,
"sex": "m",
"hobby": "abc"
}, {
"id": "12",
"name": "as2",
"age": 23,
"sex": "m",
"hobby": "abc"
}]
var expValues = {
"id": "123",
"age": 23
};
function isObjectMatched(obj) {
return aDetails.some(d => Object.entries(obj).every(([k, v]) => d[k] == v))
}
console.log(isObjectMatched(expValues))
This is a general purpose way of indexing list of objects for fast retrieval with any configuration of properties.
// javascript version
function makeIndex (arrayOfObject, listOfPropertyToIndex) {
var index = {};
index.objToKey = function (o) {
var key = [];
listOfPropertyToIndex.forEach((p) => {
key.push(""+o[p]);
});
return key.join("_");
};
arrayOfObject.forEach((o) => {
index[objToKey(o)] = o;
});
index.match = function (object) {
var key = index.objToKey(object);
if (index.hasOwnProperty(key)) {
return index[key];
};
return null;
});
return index;
}
// jscript version
function makeIndex (arrayOfObject, listOfPropertyToIndex) {
var index = {};
index.objToKey = function (o) {
var key = [];
for (var p in o) {
if (o.hasOwnProperty(p)) {
key.push(""+o[p]);
}
}
return key.join("_");
};
for (var i = 0; i < arrayOfObject.length; ++i) {
index[objToKey(arrayOfObject[i])] = o;
}
index.match = function (object) {
var key = index.objToKey(object);
if (index.hasOwnProperty(key)) {
return index[key];
};
return null;
});
return index;
}
Here is how to use it
var expValues = {
"id": "123",
"age": 23
};
var index = makeIndex(aDetails, ["id","age"]);
var obj = index.match(expValues);
if (obj) {
... obj ...
}
var index_name = makeIndex(aDetails, ["name"]);
var person = {"name":"as2"};
var obj2 = index_name.match(person);
if (obj2) {
... obj2 ...
}

convert JSON data into table based on elements seperated by \n for header elements and \t for table elements using angularJS

"results": {
"code": "SUCCESS",
"msg": [
{
"type": "TABLE",
"data": "id\tfirstname\tlastname\n1\tJack\tSmith\n2\tAdam\tJohnson\n3\tKim\tSmith\n4\tDavid\tWilliams\n5\tPeter\tDavis\n6\tJack\tSmith\n7\tAdam\tJohnson\n8\tKim\tSmith\n9\tDavid\tWilliams\n10\tPeter\tDavis\n11\tPeter\n31\tJack\tSmith\n32\tAdam\tJohnson\n33\tKim\tSmith\n34\tDavid\tWilliams\n35\tPeter\tDavis\n"
}
]
},
this is my example code,where ever we have \n consider as header elements of table and \t consider as tr elements,can you provide me any suggestion.
You might be looking something like this. In your HTML code right one ng repeat for head and other for each row of the table.
var result = {
"code": "SUCCESS",
"msg": [{
"type": "TABLE",
"data": "id\tfirstname\tlastname\n1\tJack\tSmith\n2\tAdam\tJohnson\n3\tKim\tSmith\n4\tDavid\tWilliams\n5\tPeter\tDavis\n6\tJack\tSmith\n7\tAdam\tJohnson\n8\tKim\tSmith\n9\tDavid\tWilliams\n10\tPeter\tDavis\n11\tPeter\n31\tJack\tSmith\n32\tAdam\tJohnson\n33\tKim\tSmith\n34\tDavid\tWilliams\n35\tPeter\tDavis\n"
}]
}
var format = result.msg.map((r) => {
var str = r.data;
var arr = str.split('\n');
var head = arr.splice(0, 1)[0].split('\t');
arr.pop(); // remove empty string
var data = arr.map((d) => {
return d.split('\t').reduce((obj, x, index) => {
obj[head[index]] = x;
return obj;
}, {})
})
return {
head,
data
}
});
console.log(format);

Echo "part" of array (decoded from JSON)

I'am quite new to JSON and more "advanced" arrays. Therefore I don't know what I should search for...
I have this "JSON array" (what do you call it?):
{
"id": "321123321",
"statuses": {
"data": [
{
"message": "testmessage",
"updated_time": "2012-12-25T16:33:29+0000",
"id": "123321123"
}
],
"paging": {
"previous": "1",
"next": "1"
}
}
}​
I want to create a variable from "message" that is called $message and a variable from "up_datedtime" that is called $updated.
To get id I simple:
$json_a=json_decode($string,true);
$id $json_a['id'];
And for statuses:
$json_a=json_decode($string,true);
$status = $json_a['id']['statuses'];
But when I try to get "message" I get " Cannot use string offset as an array in":
$message = $json_a['id']['statuses']['data']['message'];
How do I get $message from the array the proper way?
You can get like this
$message = $json_a['id']['statuses']['data'][0]['message'];
or you can get from loop
$dataArr = $json_a['id']['statuses']['data'];
foreach ($dataArr as $val) {
echo "message".$val['message'];
}

Resources