Remove JSON Field In MySQL [PHP] [CodeIgniter] - php

I wrote a function to accept a 'product_id' and then it will cycle through all my Json fields to find all the json objects without the id 'product id' and then I need it encode it back and update database.
currently I substituted 'product_id' with '154' since that is a 'id' I am testing to remove.
This Foreach statement I wrote gets me all the ids
$user = $this->session->userdata('user_id');
$autoOrder = $this->db->get_where('auto_order', ['user_id' => $user])->row()->products;
$temp = json_decode($autoOrder);
foreach ($temp as $value) {
$last_value = (array)$value;
foreach ($last_value as $key=> $value) {
foreach($value as $key2=>$value2) {
if ($key2 == 'id' && $value2 != '154') {
echo "Product Id: " . $value2 . "<br>";
$new_ids[] = $value2;
}
}
}
}
How can I now cycle through all the autoOrder and retrieve only the ones with 'new_ids'?
Example How The JSON Looks:
[
{
"order": {
"id": "154",
"qty": "1",
"option": "{\"color\":{\"title\":\"Color\",\"value\":null}}",
"price": "2433.62",
"name": "Race Car",
"shipping": "0",
"tax": "26",
"image": "http://localhost/products/image/34",
"coupon": ""
}
}
]

This code you wrote it's a bit complicated to understand.
Anyway, you should save the new_ids into the DataBase, and then execute the query specifying the condition to retrieve only the object without new_ids on the WHERE.

Related

remapping and grouping repeated values from an array in php

I am trying to remap an response from a query to the database and group like items in one array. for example, from this example below.
Response:
[
"Location"=> "City 1",
"AptDate"=> "2020-09-16",
"AptTime"=> "11:00",
"AptLength"=> "45",
"AptStatus"=> "1",
"Operatory"=> "1 RECALL",
"OperatoryNum"=> "2"
],
[
"Location"=> "City 2",
"AptDate"=> "2020-09-16",
"AptTime"=> "09:00",
"AptLength"=> "45",
"AptStatus"=> "1",
"Operatory"=> "1 RECALL",
"OperatoryNum"=> "2"
],
[
"Location"=> "City 1",
"AptDate"=> "2020-09-16",
"AptTime"=> "12:00",
"AptLength"-> "45",
"AptStatus"=>"1",
"Operatory"=> "1 RECALL",
"OperatoryNum"=> "2"
[,
looping through results:
$remappedData=[];
foreach ($result as $value)
{
$remappedData[] = [
'location' => $value['Location'],
// And so on
];
}
}
This doesnt really give me what i need as I am trying to group the array based on Location and add the AppDate base on that location. Something like this.
{
"Location": "City 1",
"AptDate": ["2020-09-16","2020-09-16"],
"AptTime": ["11:00","12:00"],
"AptLength": ["45","45"],
"AptStatus": ["1","1"],
"Operatory": ["1 RECALL","1 RECALL"],
"OperatoryNum": ["2","2"]
},
{
"Location": "City 2",
"AptDate": ["2020-09-16"],
"AptTime": ["09:00"],
"AptLength":[ "45"],
"AptStatus": ["1"],
"Operatory": ["1 RECALL"],
"OperatoryNum": "2"
},
So based on your scenario, you want grouping on Location and group all other attributes by keeping them in array.
foreach ($result as $value)
{
$remappedData[$value['Location']]['location'] = $value['Location'];
$remappedData[$value['Location']]['AptDate'][] = $value['AptDate']; // Notice we're creating an array here.
$remappedData[$value['Location']]['AptTime'][] = $value['AptTime'];
// so on all other attributes which needs to be grouped.
}
Note: Here we've created index as Location. If we don't want Location as key, we want as array(may be for frontend) use below code.
$temp = [];
$remappedData=[];
$intCurrentIndex = -1;
foreach ($result as $value)
{
if(isset($temp[$value['Location']])){
$oldIndex = $temp[$value['Location']];
$remappedData[$oldIndex]['AptDate'][] = $value['AptDate'];
$remappedData[$oldIndex]['AptTime'][] = $value['AptTime'];
}
else{
$temp[$value['Location']] = ++$intCurrentIndex;
$remappedData[$intCurrentIndex]['location'] = $value['Location'];
$remappedData[$intCurrentIndex]['AptDate'][] = $value['AptDate'];
$remappedData[$intCurrentIndex]['AptTime'][] = $value['AptTime'];
}
}

Problems iterating through an array

I'm having problems looking through the array data from a json file.
This is the code I have
$barcode = '0000000' //just an example this is set as a variable
$json_data = json_decode($json,true);
foreach ($json_data as $data){
$barcodejson = $data['Barcode'];
if($barcodejson == $barcode){
$alreadyscanned = 'This user is already in your contacts';
} else { do something}
}
The problem I have is its only 'looking' at the last set of data and not all of it. if I put the barcode in twice I get the error This user is already in your contacts but if I put a new one in and then the existing barcode again it doesn't work.
I'm sure its something to do with the foreach loop but can not figure it out.
my json data is structured like this :
[
{
"FirstName": "lee",
"LastName": "skelding",
"Email": "mail.mail.com",
"Barcode": "732580652913857773001",
"Phone": "00000000",
"Company": "SKELLATECH V3",
"Position": "CEO"
},
{
"FirstName": "Kenneth",
"LastName": "Brandon",
"Email": "mail.mail.com",
"Barcode": "732559813913833509001",
"Phone": null,
"Company": null,
"Position": null
},
{
"FirstName": "lee",
"LastName": "skelding",
"Email": "mail.mail.com",
"Barcode": "732580652913857773001",
"Phone": "0000000000",
"Company": "SKELLATECH V3",
"Position": "CEO"
}
]
what I want to do is see if the barcode number already exists in the json file if it does show the error if it doesn't carry on with the rest of my code and add in the new data
For the second iteration, the $alreadyscanned will be set on a user that doesn't match the condition if one that has been scanned already came before it. Either reset the value of $alreadyscanned or use array to keep a list of errors.
$alreadyscanned = [];
foreach ($json_data as $data){
$barcodejson = $data['Barcode'];
if($barcodejson == $barcode){
$alreadyscanned[$barcodejson] = 'This user is already in your contacts';
} else { do something}
}
foreach($alreadyscanned as $barcode => $error) {
var_dump($barcode. " :: " . $error);
}
Consider using break in your loop when you get into the if part: you don't want to continue once you find a duplicate:
if($barcodejson == $barcode){
$alreadyscanned = 'This user is already in your contacts';
break;
} else { do something}
Now the dosomething could be unwanted here (depending on what it does). You may need to do that in a separate loop. Something like this:
$alreadyscanned= "";
foreach ($json_data as $data){
$barcodejson = $data['Barcode'];
if($barcodejson == $barcode){
$alreadyscanned = 'This user is already in your contacts';
break;
}
}
if ($alreadyscanned=="") {
foreach ($json_data as $data){
$barcodejson = $data['Barcode'];
// do something
}
}
Lacking semicolons and stuff makes it harder to get the desired result.
Something like this might help you out on getting the data you want. Basically you can check the result of parsing by print_r-ing the json decoding process.
Then, you get a process result for each entry and, again, as a test, you can print the resulting array.
<?php
//Enter your code here, enjoy!
$json = '[
{
"FirstName": "lee",
"LastName": "skelding",
"Email": "mail.mail.com",
"Barcode": "732580652913857773001",
"Phone": "00000000",
"Company": "SKELLATECH V3",
"Position": "CEO"
},
{
"FirstName": "Kenneth",
"LastName": "Brandon",
"Email": "mail.mail.com",
"Barcode": "732559813913833509001",
"Phone": null,
"Company": null,
"Position": null
},
{
"FirstName": "lee",
"LastName": "skelding",
"Email": "mail.mail.com",
"Barcode": "732580652913857773001",
"Phone": "0000000000",
"Company": "SKELLATECH V3",
"Position": "CEO"
}]'
;
$barcode = '732580652913857773001'; //just an example this is set as a variable
$json_data = json_decode($json, true);
print_r($json_data);
foreach ($json_data as $data){
$barcodejson = $data['Barcode'];
if($barcodejson == $barcode){
$alreadyscanned[] = 'user ' . $data["Email"] .' is already in your contacts';
} else {
$alreadyscanned[] = 'This user '. $data["Email"] .' is not in your contacts';
}
}
print_r($alreadyscanned);
You need to use a function for that, so that you can use return when you find the needed barcode
function searchbarcode($json_data, $barcode)
{
foreach($json_data as $data)
{
if ( $data['Barcode'] == $barcode )
return true;
}
return false;
}
$barcode = '0000000' //just an example this is set as a variable
$json_data = json_decode($json,true);
if(searchbarcode($json_data, $barcode)){
$alreadyscanned = 'This user is already in your contacts';
} else { do something}

Select individual column json in php

{
"responseData": {
"results": [
{
"title": "sobig",
"titleNoFormatting": "test",
},
{
"title": "test 2 ",
"titleNoFormatting": "test 2sd",
},
{
"title": "asdasdasda",
"titleNoFormatting": "asdasdasd",
},
{
"title": "A Warming",
"titleNoFormatting": "A Warming",
}
.
.
.
.
{
"title": "last thing",
"titleNoFormatting": "sada",
}
],
I have json files like this.
for($i=$veri1; $i <= $veri2; $i++) {
$uri = "http://test.com/json/".$i."/0";
$json = json_decode(file_get_contents($uri));
if($json->data->price >= $nakit && $json->data->odds >= $oran)
{
I'm getting some data with this code correctly from another json file.
i want get data from first json code, if "title" == "sobig" . How can I do that.
$json->responseData->results->title == sobig is not working. How can I get data if title is sobig
$json= json_decode($response, true);
foreach ($json['responseData']['results'] as $key => $value) {
if ($value == 'sobig') {
// found it
}
}
Try this example to see if this may fix your issue.
<?php
$json = '{ "responseData": {
"result" : [
{ "title": "sobig" , "titleNo":"test"},
{ "title": "loco" , "titleNo":"test"},
{ "title": "tom" , "titleNo":"test"}
]
}}';
$jsonDecoded = json_decode($json);
foreach ($jsonDecoded->responseData->result as $key => $value) {
var_dump($value); echo '<br>';
if($value->title == 'sobig'){
echo "we did it!!";
echo "<br>";
}
}
?>
I place a couple of var dumps so you can see the stucture of your object and why you need to use the foreach

PHP get array items based on string mask

i have an array with a bunch of records like in:
{
"ID": "38424",
"heading": "Nylies soek nuwe hoof",
"typeID": "1",
"datein": "2016-09-26 12:14:16",
"edited_datein": null,
"publishDate": "2016-09-23 00:00:00",
"category": {
"ID": "1",
"heading": "News",
"typeID": "3",
"datein": "2016-09-26 11:50:06",
"edited_datein": null,
"url": "news"
},
"authorID": "592",
"tags": "skool,school,hoof,headmaster,etienne burger"
}
i have another array with "columns" i want the records to be "filtered" by
{
"ID",
"heading",
"datein",
"category|heading",
"category|url"
}
i would like the result to create a multidimensional array based on the column items:
{
"ID": "38424",
"heading": "Nylies soek nuwe hoof",
"datein": "2016-09-26 12:14:16",
"category": {
"heading": "News",
"url": "news"
}
}
how do i achieve this? i'm totally stuck on this now :( busy trying a hack of array_combine now but i dont hold much hope it would work out
so after being stuck on this for many hours.. and posting it here. i found a solution
$new_list = array();
foreach ($n as $record) {
$new_list[] = filter_columns($columns, $record);
}
and the function:
function filter_columns($columns, $record, $pre="") {
$return = array();
foreach ($record as $key => $value) { // loop through the fields in the record
$str = $pre.$key; // create a string of the current key
if (in_array($str,$columns)){
$return[$key] = $value;
}
if (is_array($value)){
$return[$key] = filter_columns($columns, $value,$key."|"); // if the value is an array recall the function but prepend the current key| to the key mask
}
}
return $return;
}

JSON Decode not showing results

I have a pretty simple bit of code to decode a json result:
code
$returnSK = returnSeoKicksLinks($s[0]);
echo "SeoKicks: " . $returnSK;
$seoKicks = json_decode($returnSK, true);
if (is_array($seoKicks) || is_object($seoKicks))
{
foreach ($seoKicks as $key => $val2)
{
$backlinks2 = $val2['UrlFrom'];
echo $backlinks2;
// backlink query and insertion
//$b = $c->query("INSERT INTO `backlinks` (`backlink_id`,`backlink_url`,`backlink_mother_url`,`backlink_date`,`backlink_from`) VALUES ('','".$backlinks2."','".$s[0]."','seokicks',NOW())");
}
}
The JSON results:
{
"Results": [
{
"Links": [
{
"Anchor": "guaranteed payday loan",
"nofollow": "1",
"UrlTo": "http:\/\/www.site.co.uk\/"
}
],
"Index": 1,
"IP": "67.139.134.215",
"UrlFrom": "http:\/\/menomena.com\/?p=240",
"DomainRank": "7"
},
{
"Links": [
{
"nofollow": "0",
"UrlTo": "http:\/\/www.site.co.uk\/",
"Anchor": "Cash Till Payday Loan"
}
],
"DomainRank": "6",
"IP": "67.222.22.156",
"Index": 2,
"UrlFrom": "http:\/\/www.aussi.org\/business\/financial-services\/loans\/"
},
{
"DomainRank": "6",
"UrlFrom": "http:\/\/www.loanranks.com\/improving-your-chances-of-receiving-payday-loans",
"Index": 3,
"IP": "173.254.28.69",
"Links": [
{
"Anchor": "guaranteed payday loans",
"nofollow": "0",
"UrlTo": "http:\/\/www.site.co.uk\/"
}
]
}
],
"Overview": {
"domainpop": "29",
"firstresultposition": 1,
"totalresultsreturned": 3,
"linkpop": "37",
"netpop": "27",
"ippop": "29"
}
}
I'm trying to get the "UrlFrom" value, but it's coming up blank, is there something i am missing here?
Without the first part of your code can not perform a test to figure out where he might be the problem. However, with this code I can print the value of UrlFrom field (passing the JSON in POST request):
$jsonPost = file_get_contents('php://input');
$decodedJson = json_decode($jsonPost);
foreach($decodedJson->Results as $key => $value) {
var_dump($value->UrlFrom);
}
You need to tell PHP to look in the "Results" array, like this:
foreach ($seoKicks['Results'] as $key => $val2)
So your code would become:
$seoKicks = json_decode($returnSK, true);
if (is_array($seoKicks) || is_object($seoKicks))
{
foreach ($seoKicks['Results'] as $key => $val2)
{
$backlinks2 = $val2['UrlFrom'];
echo $backlinks2;
// backlink query and insertion
//$b = $c->query("INSERT INTO `backlinks` (`backlink_id`,`backlink_url`,`backlink_mother_url`,`backlink_date`,`backlink_from`) VALUES ('','".$backlinks2."','".$s[0]."','seokicks',NOW())");
}
}
Some thoughts on SQL Injection
Before you uncomment the query part, please change your query to not concatenate values into the SQL. To avoid the risk of SQL injection, you should use prepared statements instead, binding the dynamic value(s) to it.

Categories