how can optimization function this code in PHP smarty?
now I've a code to confuse me, there is a simple code.
$sql_set_land = "select * from set_new_land where id_rent_house =".Tools::getValue("id_rent_house");
//print_r($sql_set_land);
$n_land = Db::rowSQL($sql_set_land,true);
$landTitle1 = $n_land['landTitle1'];
$landTitle2 = $n_land['landTitle2'];
$landBuilderNumber = $n_land['landBuilderNumber'];
$landLandMark = $n_land['landLandMark'];
$land_1 = $n_land['land_1'];
$land_2 = $n_land['land_2'];
$land_3 = $n_land['land_3'];
...
...
...
$land_30 = $n_land['land_30'];
$land_31 = $n_land['land_31'];
$land_32 = $n_land['land_32'];
when I search the code that I need to push the value.
$this->context->smarty->assign([
'park_space' =>$park_space,
'recording_data' =>$recording_data,
'clode_number' => $clode_number,
'ad_choose_top' => $ad_choose_top,
'ad_choose_type' => $ad_choose_type,
'ad_choose_payment_type' => $ad_choose_payment_type,
'ad_choose_payment_type1' => $ad_choose_payment_type1,
'landTitle1' => $landTitle1,
'landTitle2' => $landTitle2,
'landBuilderNumber' => $landBuilderNumber,
'landLandMark' => $landLandMark,
'land_1' => $land_1,
'land_2' => $land_2,
'land_3' => $land_3,
...
...
...
'land_30' => $land_30,
'land_31' => $land_31,
'land_32' => $land_32,
how can optimization function? Can I write to array? if It's can write into array, how can I do?
Your problem is not in the PHP code, it is in the design of your database. Any time you need to have numbers in column names is a sign that you've failed to normalize your data.
If you expanded the *, which is generally good practice to avoid surprises when you make changes to your database, you would have to write this:
select
landTitle1,
landTitle2,
landBuilderNumber,
landLandMark,
land_1,
land_2,
land_3,
land_4,
land_5,
land_6,
land_7,
land_8,
land_9,
land_10,
land_11,
land_12,
land_13,
land_14,
land_15,
land_16,
land_17,
land_18,
land_19,
land_20,
land_21,
land_22,
land_23,
land_24,
land_25,
land_26,
land_27,
land_28,
land_29,
land_30,
land_31,
land_32
from set_new_land
where id_rent_house = :id
With a properly normalised database, you would instead write something like this:
select
SND.landTitle1,
SND.landTitle2,
SND.landBuilderNumber,
SND.landLandMark,
L.landNumber,
L.land
from set_new_land as SND
join lands as L
On L.set_new_land_id = SND.set_new_land_id
where SND.id_rent_house = :id
Then in PHP, you can use the array_column function:
$lands = array_column($dbResults, 'land');
// or, if the land numbers are important
$lands = array_column($dbResults, 'land', 'landNumber');
If you can't fix your data, though, you can transform it into a more sensible form in PHP, with a loop that counts from 1 to 32:
$lands = [];
for ( $landNumber=1; $landNumber<=32; $landNumber++ ) {
$columnName = 'land_' . $landNumber;
$lands[] = $messyDbResults[ $columnName ];
}
Related
I am having the foreach loop that will run minimum 2000 loops
foreach ($giftCardSchemeData as $keypreload => $preload) {
for ($i=0; $i <$preload['quantity'] ; $i++) {
$cardid = new CarddetailsId($uuidGenerator->generate());
$cardnumber = self::getCardNumber();
$cardexistencetype = ($key == "giftCardSchemeData") ? "Physical" : "E-Card" ;
$giftCardSchemeDataDb = array('preload' => array('value' => $preload['value'], 'expirymonths' => $preload['expiryMonths']));
$otherdata = array('cardnumber' => $cardnumber, 'cardexistencetype' => $cardexistencetype, 'isgiftcard' => true , 'giftcardamount' => $preload['value'],'giftCardSchemeData' => json_encode($giftCardSchemeDataDb), 'expirymonths' => $preload['expiryMonths'], 'isloyaltycard' => false, 'loyaltypoints' => null,'loyaltyCardSchemeData' => null, 'loyaltyRedeemAmount' => null, 'pinnumber' => mt_rand(100000,999999));
$output = array_merge($data, $otherdata);
// var_dump($output);
$carddetailsRepository = $this->get('oloy.carddetails.repository');
$carddetails = $carddetailsRepository->findByCardnumber($cardnumber);
if (!$carddetails) {
$commandBus->dispatch(
new CreateCarddetails($cardid, $output)
);
} else {
self::generateCardFunctionForErrorException($cardid, $output, $commandBus);
}
}
}
Like above foreach I am having totally 5 of them. When I call the function each time the 5 foreach runs and then return the response. It take more time and the php maximum execution time occurs.
Is there a any way to send the response and then we could run the foreach in server side and not creating the maximum execution time issue.Also need an optimization for the foreach.
Also In symfony I have tried the try catch method for the existence check in the above code it return the Entity closed Error. I have teprorily used the existence check in Db but need an optimization
There seems to be a lot wrong (or to be optimized) with this code, but let's focus on your questions:
First I think this code shouldn't be in code that will be triggered by a visitor.
You should seperate 2 processes:
1. A cronjob that runs that will generate everything that must be generated and saved that generated info to a database. The cronjob can take as much time as it needs. Look at Symfony's console components
2. A page that displays only the generated info by fetching it from the database and passing it to a Twig template.
However, looking at the code you posted I think it can be greatly optimized as is. You seem to have a foreach loop that fetches variable data, and in that you have a for-loop that does not seem to generate much variability at all.
So most of the code inside the for loop is now being executed over and over again without making any actual changes.
Here is a concept that would give much higher performance. Ofcourse since I don't know the actual context of your code you will have to "fix it".
$carddetailsRepository = $this->get('oloy.carddetails.repository');
$cardexistencetype = ($key == "giftCardSchemeData") ? "Physical" : "E-Card";
foreach ($giftCardSchemeData as $keypreload => $preload) {
$cardnumber = self::getCardNumber();
$carddetails = $carddetailsRepository->findByCardnumber($cardnumber);
$giftCardSchemeDataDb = array('preload' => array('value' =>
$preload['value'], 'expirymonths' => $preload['expiryMonths']));
$otherdata = array('cardnumber' => $cardnumber, 'cardexistencetype' =>
$cardexistencetype, 'isgiftcard' => true , 'giftcardamount' =>
$preload['value'],'giftCardSchemeData' =>
json_encode($giftCardSchemeDataDb), 'expirymonths' =>
$preload['expiryMonths'], 'isloyaltycard' => false, 'loyaltypoints' =>
null,'loyaltyCardSchemeData' => null, 'loyaltyRedeemAmount' => null,
'pinnumber' => 0);
$output = array_merge($data, $otherdata);
for ($i=0; $i <$preload['quantity'] ; $i++) {
$cardid = new CarddetailsId($uuidGenerator->generate());
$output['pinnumber'] = mt_rand(100000,999999);
if (!$carddetails) {
$commandBus->dispatch(
new CreateCarddetails($cardid, $output)
);
} else {
self::generateCardFunctionForErrorException($cardid, $output, $commandBus);
}
}
}
Also: if in this code you are triggering any database inserts or updates, you don't want to trigger them each iteration. You will want to start some kind of database transaction and flush the queries each X iterations instead.
The output I am trying to receive is
"The Interest Rates are:
0.0525
0.0550
0.0575"
This will continue to $InterestRate7 value. I tried to link the new array elements with the old interest rate ($InterestRate1 = 0.0525; $RatesArray[1] = $InterestRate1) but it still does not work for me.Here is my code for extra help.
<?php
$InterestRate1 = 0.0525;
$InterestRate2 = 0.0550;
$InterestRate3 = 0.0575;
$InterestRate4 = 0.0600;
$InterestRate5 = 0.0625;
$InterestRate6 = 0.0650;
$InterestRate7 = 0.0700;
$RatesArray = array(
$RatesArray[1] = "0.0525";
$RatesArray[2] = "0.0550";
$RatesArray[3] = "0.0575";
$RatesArray[4] = "0.0600";
$RatesArray[5] = "0.0625";
$RatesArray[6] = "0.0650";
$RatesArray[7] = "0.0700";);
echo $RatesArray[1];
?>
The array() construct doesn't work quite like what you have here. Try something similar to the example in the php documentation http://php.net/manual/en/language.types.array.php
$RatesArray = array(
1 => "0.0525",
2 => "0.0550",
3 => "0.0575");
I am having troubles converting a string which contains tab delimited CSV output
into an array. While using the following code :
$data = stream_get_contents($request->getShipmentReport());
I get back data as following:
Date Shipped Comments Feedback Arrived on Time
5/11/15 2 comment response Yes
Now I would like to process this data into an array with the returned headers(line 1) as the index containing the value for each line which follows after that.
I am trying to end up with something like this :
$line['Date'] = 5/11/15
$line['Shipped'] = 2
$line['Feedback'] = response
$line['Arrived on Time'] yes
What would be the best way to achieve this ?
I recommend using a library for handling CSV for example the CSV-Package by The League of Extraordinary Packages
You can pass your data and start working with array structures right away:
$csvString = stream_get_contents($request->getShipmentReport());
$csvReader = \League\Csv\Reader::createFromString($csvString);
$data = $csvReader->fetchAssoc(
array('Date', 'Shipped', 'Comments', 'Feedback', 'Arrived on Time')
);
// Or since line 0 contains header
$data = $csvReader->fetchAssoc(0); // 0 is offset of dataset containing keys
Now your data should be in a structure like:
$data = array(
array(
'Date' => '5/11/15',
'Shipped' => '2',
...
),
array(
...
)
);
You can even filter out specific datasets and all kinds of fancy stuff. Just check the documentation I linked to.
League CSV reader gives me a bad result. I use this instead:
$csvReportString = stream_get_contents($request->getReport());
$csvReportRows = explode("\n", $csvReportString);
$report = [];
foreach ($csvReportRows as $c) {
var_dump($c);
if ($c) { $report[] = str_getcsv($c, "\t");}
}
var_dump($report);
I'm having some troubles with NuSOAP trying to send duplicate tags. This is the code i need to send :
<PartNumbers>
<string>string1</string>
<string>string2</string>
</PartNumbers>
I'm doing the call with this code:
$pn[] = 'APPSP2101V2';
$pn[] = 'ME665Y/A';
$PartNumbers = array( 'PartNumbers' => array('string' => $pn));
$result = $client->call('GetDataSheetsLastUpdate', $PartNumbers );
I'm sending those two PartNumbers but instead of send the two codes it's sending the last one "ME665Y/A"
Also if i try
$PartNumbers = array( 'PartNumbers' => array('string' => 'APPSP2101V2', 'string' => 'ME665Y/A'));
$result = $client->call('GetDataSheetsLastUpdate', $PartNumbers );
Only send the last string.
How can i make an array with the same keys but different value to make the XML look like in the beggining of the question.
Thank you in advance to all
With the following code:
$pn[] = 'APPSP2101V2';
$pn[] = 'ME665Y/A';
$PartNumbers = array( 'PartNumbers' => array('string' => $pn));
$result = $client->call('GetDataSheetsLastUpdate', $PartNumbers );
Works perfect , the problema was in the webservice.. if the P/N isn't correct only return the P/N with information on it.
I have been trying to build a graph using open Flash Chart 2 in Drupal (Well, the problem isn't related to Drupal or the graphs and chart module)
For the graph I am fetching the data from a MySQL database. Below is the function which gets the data and generates the graph:
function my_module_charts_graphs_test() {
global $user;
$uname = $user->name;
$sql = "Select total_calorie from health_calorie_consumed where name = '%s'";
$result = db_query($sql,$uname);
while($row = db_fetch_array($result))
{
$data[] = $row[total_calorie];
}
$canvas = charts_graphs_get_graph('open-flash');
$canvas->title = "OpenFlashCharts Chart";
$canvas->type = "bar_3d";
$canvas->y_legend = "Y Legend";
$canvas->colour = '#808000';
$canvas->width = 700;
$canvas->height = 300;
$canvas->y_max=1000;
$canvas->y_min=0;
$canvas->y_step=100;
$canvas->series = array(
'Some Value' => array(923,623,73,92,5,722,643,156,345),
//'Page Views' => array_values($data),
);
$canvas->x_labels = array('one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine');
// $canvas->x_labels = array_values($data);
$out = $canvas->get_chart();
return $out;
}
When I run the code, I get the below graph:
So, it works perfectly with a locally declared array. But I need to use the array from SQL. Hence I uncomment and change $canvas->c_labels and $canvas->series:
$canvas->x_labels = array_values($data); //$data is array from sql query
'Page Views' => array_values($data)
Now, to my surprise, I get the below graph:
As we can see, the x_axis values are right as per the query but y_axis says the same values as infinity. Why does it do this?
There is another face to this strange problem. Initially I thought that this approach may not work with $canvas->series, but I tried the below code and it worked perfectly:
$array = array(0,0,117,207,130,260,207); //these values are that are fetched from sql
$canvas->series = array(
'some values'=>array_values($array),
);
So this "infinity" problem only appears for arrays fetched from SQL queries and only for the Y axis.
print_r($data) of my SQL is as follows:
Array ( [0] => 0 [1] => 0 [2] => 117 [3] => 207 [4] => 130 [5] => 260 [6] => 207 )
Below are some other combinations I tried for $canvas->series and failed...
$test = implode(",",$data); // $data is the array fetched from sql
$abcd = "array(".$test.")"; // array(0,0,117,207,130,260,207)
$canvas->series=>array(
'some value'=>print($abcd), //i tried to print those values in standard format..:p
);
'some values'=>$abcd, // doesn't work..!
'some values'=>$data, // doesn't work.!
Thus I tried everything I can think of with no luck.
wow.. Finally I found the answer, thanks to drupal forums..:)
As it turns out its a type issue..! i.e, if I use the following code, it works..!!
<?php
$data[] = (int) $row[total_calorie];
?>
I have no idea why is it a type issue. or the reason why this works, but it does solve my problem...! Thanks to everybody for helping me solve it..:)
Try insert
$data = array();
Before the while($row = db_fetch_array($result))
And use just
'Page Views' => $data