I am using ajax to get a json response and fill my datatable however for some reason some random values in the json have a line break. In the database the value will be lets say "90 g per 100 m of row" but it outputs in the json like below.
All other rows are fine and here is how I make the json object.
for($i = 0; $i < $numRows; $i++) {
$chemicals = getPestsChemicals($connection, $rows[$i]['code']);
$chemNames = '';
foreach($chemicals as $chem) {
$chemNames .= $chem['chemical'].'<br>';
}
$mrls = getPestsMrls($connection, $rows[$i]['code']);
$mrlNames = '';
foreach($mrls as $mrl) {
$mrlNames .= (strlen($mrl['mrl']) == 1 ? $mrl['mrl'].".0" : $mrl['mrl']).'<br>';
}
if($i != $numRows-1) {
$body .= '
{
"crop": "'.$rows[$i]['crop'].'",
"diseases": "'.$rows[$i]['pest_name'].'",
"chemical": "'.$chemNames.'",
"product": "'.$rows[$i]['product']." ".($rows[$i]['footnote'] != NULL ? '<sup class=\"text-danger font-weight-bold\">'.$rows[$i]['footnote'].'</sup>' : NULL ).'",
"rate": "'.$rows[$i]['rate'].'",
"max_no": "'.$rows[$i]['max_no'].'",
"hi": "'.$rows[$i]['hi'].'",
"mrl": "'.$mrlNames.'",
"pcs_no": "'.($rows[$i]['pcs_no'] == 0 ? 'DR' : '0'.$rows[$i]['pcs_no']).'",
"supplier": "'.$rows[$i]['supplier'].'",
"use_by_date": "'.$rows[$i]['use_by_date'].'"
},
';
} else {
$body .= '
{
"crop": "'.$rows[$i]['crop'].'",
"diseases": "'.$rows[$i]['pest_name'].'",
"chemical": "N/A",
"product": "'.$rows[$i]['product']." ".($rows[$i]['footnote'] != NULL ? '<sup class=\"text-danger font-weight-bold\">'.$rows[$i]['footnote'].'</sup>' : NULL).'",
"rate": "'.$rows[$i]['rate'].'",
"max_no": "'.$rows[$i]['max_no'].'",
"hi": "'.$rows[$i]['hi'].'",
"mrl": "N/A",
"pcs_no": "'.($rows[$i]['pcs_no'] == 0 ? 'DR' : '0'.$rows[$i]['pcs_no']).'",
"supplier": "'.$rows[$i]['supplier'].'",
"use_by_date": "'.$rows[$i]['use_by_date'].'"
}
';
}
}
I have tried to wrap the relevant row in strval or json_encode but no success. Also here is how it looks in the db
For a quick fix try
$rate_string = (string) $rows[$i]['rate'];
then just replace:
"rate": "'.$rate_string .'",
If it fails to cast into string you might have a further clue.
Related
The form of the incoming json data:
{
"statusCode": 200,
"message": "success",
"result": [
{
"longitude": -87.06687,
"start_location_latitude": 20.63589,
"start_location_longitude": -87.06687,
"end_location_latitude": 20.63589,
"end_location_longitude": -87.06687,
"highlights": [
{
"title": "Oh Yes...Mezcal Shots",
"url": "https://phoenix-cdn.azureedge.net/phoenix-blob-public-exps/1396_Mezcal_Shot.jpg"
},
{
"title": "Playa Del Carmen Beachfront",
"url": "https://phoenix-cdn.azureedge.net/phoenix-blob-public-exps/1396_Playa_Del_Carmen-Beach_Punta_Esmeralda.jpg"
},
{
"title": "Visit the Market",
"url": "https://phoenix-cdn.azureedge.net/phoenix-blob-public-exps/1396_Playa_Del_Carmen.jpg"
}
]
}
]
}
This incoming data is combined into a single line.
https://phoenix-cdn.azureedge.net/phoenix-blob-public-exps/1396_Mezcal_Shot.jpghttps://phoenix-cdn.azureedge.net/phoenix-blob-public-exps/1396_Playa_Del_Carmen-Beach_Punta_Esmeralda.jpghttps://phoenix-cdn.azureedge.net/phoenix-blob-public-exps/1396_Playa_Del_Carmen.jpg
But what I want to do is to get the first 4 of these data, for example, by throwing them into separate variables and using them. However, I was never able to do that.
My code:
foreach($UnlockData as $highlights)
{
foreach($highlights as $SingleImage)
{
if(strlen($SingleImage['url']) > 3) {
echo $SingleImage['url'];
}
}
}
This will return the first 4 highlights from each entry in result. I am using the json object vs array because I find using it as objects makes for easier to read code.
<?php
$json = json_decode($incomingJSON);
foreach ($json->result as $result) {
$ctr = 0 ;
foreach($result->highlights as $highlight) {
if (strlen($highlight->url) < 5) continue;
echo "<P>" . $highlight->title. " - " . $highlight->url;
$ctr ++;
if ($ctr>3) break;
}
}
If there is ever only one result then just get all the url from highlights (not clear why the strlen):
$urls = array_column($array['result'][0]['highlights'], 'url');
foreach($urls as $url) {
if(strlen($url) > 3) {
echo $url;
}
}
If there are multiple result then get all the highlights and then get all the url from that:
$urls = array_column(array_column($array['result'], 'highlights'), 'url']);
I have a JSON file which structure looks like this (very simplified):
[
{
"customerId": "M12345",
"houses": [
{
"id": "OBJ12345_1731321200",
"status": {
"id": "4",
"name": "Sold"
}
],
"plots": [
{
"id": "OBJ12345_1771637082",
"status": {
"id": "4",
"name": "Sold"
}
],
"projects": [],
"farms": [],
"commercialPropertys": [],
"condominiums": [],
"foreignProperties": [],
"premises": []
}
]
I have figured out how to count how many "houses" or "plots" there is:
$content = file_get_contents('estateList/estateList.json');
$GetEstateList = json_decode($content);
count($GetEstateList[0]["houses"]);
count($GetEstateList[0]["plots"]);
BUT Trying to figure out using php how to count how many objects which have a condition status(id:4)
I think you will need to use a loop in order to count the objects, i would use a foreach loop, bellow is an example :
$count = 0;
foreach ( $GetEstateList[0] as $key => $value){
if (isset($value['status']) && $value['status']['id'] === "4") {
$count++;
}
}
First, you need to enter the GetEstateList array, then you need to do a cycle for each type (for now types showed are plots and houses), then you need another cycle, because each type is an array of elements and can have more than one estate.
So, try this code:
// Counter variable for condition expressed after (status == 4)
$counter = 0;
// Enter the array and get `customerId`, `houses` and `plots`,
// but we only need the types of estate, so only `houses` and `plots`, in this case
foreach ( $GetEstateList as $estate_array => $array_attr ) {
// We only need `houses` and `plots` (increasing algorithm performance)
if ( $array_attr == "houses" || $array_attr == "plots" ) {
// We're checking all types of estates (all `houses` and all `plots`)
foreach ( $array_attr as $type => $parameter ) {
// So, we can get `status` of every estate
if ( $parameter == "status") {
// And finally we can get `id` for each estate `status`
if ( $parameter["id"] == "4" ) {
$counter++;
}
}
}
}
}
Notice: the code above cannot work if the written JSON structure is too different from the original.
I figured it out myself...
Maybe not the "correct" way but it works! :)
Feel free to comment on any improvement or modifications...
$StatusCount = 0;
foreach ($GetEstateList[0] as $GetEstateType) {
foreach ($GetEstateType as $GetEstate) {
if ($GetEstate["status"]["id"] == "4") {
$StatusCount++;
}
}
}
Im using Yii createCommand QueryBuilder and constructing below insert query, below code works like charm (inserts 6000 records in 3 secs) but after sometime its speed becomes very slow.
My code:
$taskmodel = TaskModel::model()->findAll($cri); // filtering using some criteria
$now = new DateTime();
foreach( $taskmodel as $tsk ) {
$recall_date = $tsk['recall_date'] == "" ? "null" : '"'.$tsk['recall_date'].'"';
$recall_agent = $tsk['recall_agent_id'] == "" ? "null" : $tsk['recall_agent_id'];
$next_date = $tsk['next_action_date'] == "" ? "null" : '"'.$tsk['next_action_date'].'"';
$pc_color = $tsk['postcode_color'] == "" ? "null" : '"'.$tsk['postcode_color'].'"';
$cpc_id = $tsk['crm_campaign_post_code_id'] == "" ? "null" : $tsk['crm_campaign_post_code_id'];
$priority = $tsk['priority'] == "" ? 10 : $tsk['priority'];
$field1 = "null" ;
$field2 = "null"
$field3 = "null"
$field4 = "null" ;
$contact_timezone = $tsk['contact_timezone'] == "" ? "''" : '"'.$tsk['contact_timezone'].'"';
$sql[] = '('.$tsk['crm_task_id'].', '.$tsk['crm_campaign_id'].', "'.$tsk['crm_contact_id'].'", "'.$now->format('Y-m-d H:i:s').'", "'.$now->format('Y-m-d H:i:s').'
", '.$tsk['crm_filter_id'].', '.$tsk['current_status'].', '.$priority.', '.$recall_date.', '.$recall_agent.', '.$next_date.
', '.$pc_color.', '.$cpc_id.', '.$sort.', '.$field1.', '.$field2.', '.$field3.', '.$field4.', '.$contact_timezone.', '.$tsk['is_active'].')';
}
if(sizeof($sql) > 0){
$ins ='INSERT INTO crm_pending_task (crm_task_id, crm_campaign_id,crm_contact_id,created,updated,crm_filter_id,
current_status,priority,recall_date,recall_agent_id,next_action_date,postcode_color,crm_campaign_post_code_id,sort,
field1,field2,field3,field4,contact_timezone,is_active) VALUES '.implode(',', $sql);
Yii::app()->db->createCommand($ins)->execute();
}
i found something interesting, after inserting 50000 records it becomes slow !!! why is it so ???
How to improve insert query speed till it finishes all insertion ?
I think is because your request is taking too much memory and you are swapping.
To free some memory you shouldt try to enable Gc and launch it in your foreach (maybe not at each iteration)
gc_enable();
gc_collect_cycles();
Perhaps trying inserting smaller chunks into the database.
foreach( $taskmodel as $tsk ) {
$recall_date = $tsk['recall_date'] == "" ? "null" : '"'.$tsk['recall_date'].'"';
$recall_agent = $tsk['recall_agent_id'] == "" ? "null" : $tsk['recall_agent_id'];
$next_date = $tsk['next_action_date'] == "" ? "null" : '"'.$tsk['next_action_date'].'"';
$pc_color = $tsk['postcode_color'] == "" ? "null" : '"'.$tsk['postcode_color'].'"';
$cpc_id = $tsk['crm_campaign_post_code_id'] == "" ? "null" : $tsk['crm_campaign_post_code_id'];
$priority = $tsk['priority'] == "" ? 10 : $tsk['priority'];
$field1 = "null" ;
$field2 = "null"
$field3 = "null"
$field4 = "null" ;
$contact_timezone = $tsk['contact_timezone'] == "" ? "''" : '"'.$tsk['contact_timezone'].'"';
$sql[] = '('.$tsk['crm_task_id'].', '.$tsk['crm_campaign_id'].', "'.$tsk['crm_contact_id'].'", "'.$now->format('Y-m-d H:i:s').'", "'.$now->format('Y-m-d H:i:s').'
", '.$tsk['crm_filter_id'].', '.$tsk['current_status'].', '.$priority.', '.$recall_date.', '.$recall_agent.', '.$next_date.
', '.$pc_color.', '.$cpc_id.', '.$sort.', '.$field1.', '.$field2.', '.$field3.', '.$field4.', '.$contact_timezone.', '.$tsk['is_active'].')';
}
$recordCount = sizeof($sql);
$sliceSize = 250;
for($x = 0; $x < $recordCount; $x += $sliceSize) {
$ins = sprintf('
INSERT INTO
crm_pending_task
(
crm_task_id, crm_campaign_id, crm_contact_id, created,updated,
crm_filter_id, current_status, priority, recall_date, recall_agent_id,
next_action_date, postcode_color, crm_campaign_post_code_id, sort,
field1, field2, field3, field4, contact_timezone, is_active
)
VALUES
%s; ', implode(',', array_slice($sql, $x, $sliceSize));
Yii::app()->db->createCommand($ins)->execute();
}
}
I know there are like hundreds similar questions on this site, but I just can't get my code working...
I have this JSON
{
"version":"1.0.0",
"buildDate":20131029,
"buildTime":165127,
"lockPath":"..\\var\\lock",
"scriptPath":"..\\var\\lock",
"connections":
[
{
"name":"o016561",
"bez":"GEW-NRW",
"type":"OVPN"
},
{
"name":"o016482",
"bez":"GEW-BW",
"type":"OVPN"
},
{
"name":"o019998",
"bez":"GEW-SH",
"type":"OVPN"
}
]}
how can I access the "name" values to check if there's an existing file with an equal name?
I tried
$json_config_data = json_decode(file_get_contents($json_path,true));
foreach($json_config_data->connections as $connectionName)
{
if($connectionName->name == $fileName)
{
$status = 1;
}
else
{
$status = 0;
}
}
but I always get $status = 0...
I think there's an easy solution for this, but I'm pretty new to PHP so I'd be glad for any kind of help.
Thanks in advice
You're resetting the value of $status for every iteration which means that the last connection HAS to be the correct one. You're probably looking for a break statement.
$json_config_data = json_decode(file_get_contents($json_path,true));
$status = 0; //Default to 0
foreach($json_config_data->connections as $connectionName)
{
if($connectionName->name == $fileName)
{
$status = 1;
break; //End the loop
}
}
This would only result in $status == 1 if the final name matched your requirements; otherwise you're setting $status back to 0. You should break out of the loop when you find a match:
$status = 0;
foreach ($json_config_data->connections as $connectionName) {
if ($connectionName->name == $fileName) {
$status = 1;
break; // this breaks out of the foreach loop
}
}
I am very very new at PHP and I don't even know JSON. Also, I couldn't know how to express it in the question. My question is;
I need to make a JSON data with PHP with the data from database. So what my expected output is like;
{ "canFireAPICalls": true, "ads": { "servers": [ { "type": "OpenX", "apiAddress": "http://openx.openvideoads.org/openx/www/delivery/fc.php", } ], "schedule": [ { "zone": "5", "position": "pre-roll" }, { "zone": "33", "width": 450, "height": 50, "startTime": "00:00:05", "duration": "15" } ], } }
What I wrote in PHP is;
while ($doZones->fetch() && $row = $doZones->toArray()) {
$row_array['zone'] = $row['zoneid'];
$row_array['position'] = $row['delivery'];
if($row['delivery'] == 0 || $row['delivery'] == 1 || $row['delivery'] == 4 ){
$row_array['width'] = $row['width'];
$row_array['height'] = $row['height'];
}
array_push($return_arr,$row_array);
}
$resultJSON .=json_encode($return_arr);
And my output is
{ "canFireAPICalls": true, "ads": { "servers": [ { "type": "OpenX", "apiAddress": "http://openx.openvideoads.org/openx/www/delivery/fc.php", } ], "schedule":[{"zone":"3","position":"6"},{"zone":"2","position":"6"},{"zone":"4","position":"6"},{"zone":"5","position":"6"},{"zone":"6","position":"1","width":"468","height":"60"},{"zone":"7","position":"6","width":"468","height":"60"},{"zone":"8","position":"0","width":"120","height":"600"},{"zone":"9","position":"7","width":"120","height":"600"},{"zone":"10","position":"0","width":"120","height":"600"},{"zone":"11","position":"0","width":"728","height":"90"},{"zone":"12","position":"0","width":"120","height":"90"},{"zone":"13","position":"1","width":"468","height":"60"},{"zone":"14","position":"3","width":"468","height":"60"},{"zone":"15","position":"1","width":"560","height":"40"},{"zone":"16","position":"4","width":"468","height":"60"},{"zone":"17","position":"6","width":"468","height":"60"},{"zone":"18","position":"6","width":"468","height":"60"},{"zone":"19","position":"7","width":"468","height":"60"}] } }
If you noticed, even there shouldn't be width and height, there is. I only want the width and height when $row['delivery'] is 0,1 or 4. But, once it finds a value 0,1 or 4, then even if the next row is not 0,1 or 4, it prints width and height. Is there a way to fix this? I don't know any JSON and just started with PHP. Right now, I don't care about the missing tags like duration or writing pre-roll. I will take care of them after I fix this.
The problem is in your php. You don't reset the values of your array $row_array, so the first time the condition is true, the values of height and width are kept in the array.
You can fix it this way :
while ($doZones->fetch() && $row = $doZones->toArray()) {
$row_array['zone'] = $row['zoneid'];
$row_array['position'] = $row['delivery'];
if($row['delivery'] == 0 || $row['delivery'] == 1 || $row['delivery'] == 4 ){
$row_array['width'] = $row['width'];
$row_array['height'] = $row['height'];
}
array_push($return_arr,$row_array);
// Add this line to reset the array and reset width / height
$row_array = array();
}
$resultJSON .=json_encode($return_arr);