Below is the code which I'm willing to compress:
$somefield = 0;
if ($config->get('var1.one') && is_numeric($config->get('var1.one'))) {
$somefield = $this->entityManager->getStorage('node')->load($config->get('var1.one'));
}
$different_field = 0;
if ($config->get('var2.two') && is_numeric($config->get('var2.two'))) {
$different_field = $this->entityManager->getStorage('node')->load($config->get('var2.two'));
}
After your comment, what I think you want is something like:
$somefield = checkVar("var1.one");
$different_field = checkVar("var2.two");
function checkVar($name) {
if ($config->get($name) && is_numeric($config->get($name))) {
return $this->entityManager->getStorage('node')->load($config->get($name));
} else {
return 0;
}
}
I think this what you wanted. The names I used are not necessarily the best ones, you should use some better suited to the actual use of the function.
Another way to do it.
$field = [];
$array= ['var1.one', 'var2.two'];
for ($i = 0; $i < count($array); $i++) {
if ( $config->get($array[i] ) && is_numeric($config->get($array[$i])) )
{
array_push($field, $this->entityManager->getStorage('node')->load($config->get($array[$i])));
}
}
Related
while(strcasecmp(trim($l),"end")!=0 && $pos<count($getjkl))
{
$pieces = preg_split("/[\s]+/",trim($l));
if(substr($pieces[0],0,1)!="#" && count($pieces)>1)
{
if(file_exists($getprj."/mat/".str_replace("\\", "/",$pieces[1])))
{
$found = false;
for($j=0; $j<count($compilefiles); $j++)
{
if(strcasecmp($compilefiles[$j][2],"mat\\".$pieces[1])==0)
$found=true;
}
if($found==false)
{
$compilefiles[$numfiles][0] = $fileoffset;
$compilefiles[$numfiles][1] = filesize($getprj."/mat/".str_replace("\\", "/",$pieces[1]));
$compilefiles[$numfiles][2] = "mat\\".$pieces[1];
$fileoffset = $fileoffset + $compilefiles[$numfiles][1];
$numfiles++;
}
}
else if(file_exists($getprj."/3do/mat/".str_replace("\\", "/",$pieces[1])))
{
$found = false;
for($j=0; $j<count($compilefiles); $j++)
{
if(strcasecmp($compilefiles[$j][2],"3do\\mat\\".$pieces[1])==0)
$found=true;
}
if($found==false)
{
$compilefiles[$numfiles][0] = $fileoffset;
$compilefiles[$numfiles][1] = filesize($getprj."/3do/mat/".str_replace("\\", "/",$pieces[1]));
$compilefiles[$numfiles][2] = "3do\\mat\\".$pieces[1];
$fileoffset = $fileoffset + $compilefiles[$numfiles][1];
$numfiles++;
}
}
}
$l=$getjkl[$pos];
$pos++;
}
This here is a piece of code where I read a file and check if the listed files in there exist. Well, I actually read the file like this:
$getjkl = preg_split("/\R/",file_get_contents($levelfile));
and then step through it line by line. This block is repeated 10 times with slight differences for different file types. I then realize that I'll have to go through some file types a few more times because more file names appear later on. But instead of repeating this code, I thought I could just call this code block several times. So I do something like this:
while(strcasecmp(trim($l),"end")!=0 && $pos<count($getjkl))
{
$pieces = preg_split("/[\s]+/",trim($l));
if(substr($pieces[0],0,1)!="#" && count($pieces)>1)
{
GetMats($getprj,$pieces,$compilefiles,$numfiles,$fileoffset);
}
$l=$getjkl[$pos];
$pos++;
}
function GetMats(&$getprj,&$pieces,&$compilefiles,&$numfiles,&$fileoffset)
{
if(file_exists($getprj."/mat/".str_replace("\\", "/",$pieces[1])))
{
$found = false;
for($j=0; $j<count($compilefiles); $j++)
{
if(strcasecmp($compilefiles[$j][2],"mat\\".$pieces[1])==0)
$found=true;
}
if($found==false)
{
$compilefiles[$numfiles][0] = $fileoffset;
$compilefiles[$numfiles][1] = filesize($getprj."/mat/".str_replace("\\", "/",$pieces[1]));
$compilefiles[$numfiles][2] = "mat\\".$pieces[1];
$fileoffset = $fileoffset + $compilefiles[$numfiles][1];
$numfiles++;
}
}
else if(file_exists($getprj."/3do/mat/".str_replace("\\", "/",$pieces[1])))
{
$found = false;
for($j=0; $j<count($compilefiles); $j++)
{
if(strcasecmp($compilefiles[$j][2],"3do\\mat\\".$pieces[1])==0)
$found=true;
}
if($found==false)
{
$compilefiles[$numfiles][0] = $fileoffset;
$compilefiles[$numfiles][1] = filesize($getprj."/3do/mat/".str_replace("\\", "/",$pieces[1]));
$compilefiles[$numfiles][2] = "3do\\mat\\".$pieces[1];
$fileoffset = $fileoffset + $compilefiles[$numfiles][1];
$numfiles++;
}
}
}
Took me a while to figure out that the variables don't automatically follow and get changed in a function unless I &reference them. However, after doing this to two code blocks, it seems to slow down extra much so that I hit the 30 second execution limit. Are functions really that much more expensive? And what would be the best way to call back to repeating code while still retaining the arrays and counters?
$getprj = string = folder
$pieces = array
$compilefiles = array (set a ways back)
$numfiles = int ( = 0 from the start) (counter)
$fileoffset = int ( = 0 from the start) (counter)
I am trying to calculate a value based on a price field in an entity reference field.
I currently have this, which works...
if (isset($entity->field_choose_a_package['und'][0]['target_id'])) {
$package1nid = $entity->field_choose_a_package['und'][0]['target_id'];
$package1 = node_load($package1nid);
$package1price = $package1->field_price['und'][0]['value'];
} else {
$package1price = 0;
}
if (isset($entity->field_choose_a_package['und'][1]['target_id'])) {
$package2nid = $entity->field_choose_a_package['und'][1]['target_id'];
$package2 = node_load($package2nid);
$package2price = $package2->field_price['und'][0]['value'];
} else {
$package2price = 0;
}
if (isset($entity->field_choose_a_package['und'][2]['target_id'])) {
$package3nid = $entity->field_choose_a_package['und'][2]['target_id'];
$package3 = node_load($package3nid);
$package3price = $package3->field_price['und'][0]['value'];
} else {
$package3price = 0;
}
$packagestotal = $package1price + $package2price + $package3price;
$entity_field[0]['value'] = $packagestotal;
However, there could be an unlimited amount of packages added, and rather than me replicate the code for 20+ packages to try and cover my bases, there must be a way I can do a for each loop.
I have tried something like this,
$arr = $entity->field_choose_a_package['und'];
foreach ($arr as &$value) {
if (isset($entity->field_choose_a_package['und'][$value]['target_id'])) {
$package1nid = $entity->field_choose_a_package['und'][$value]['target_id'];
$package1 = node_load($package1nid);
$package1price = $package1->field_price['und'][$value]['value'];
} else {
$package1price = 0;
}
}
unset($value);
but I cant figure out how to increment the variables, or if even need to? Can i just calculate the totals from the foreach?
$packagestotal = 0;
$numPackages = 3;
for($i = 0; $i <= $numPackages; $i++) {
if(isset($entity->field_choose_a_package['und'][$i]['target_id'])) {
${'package' . $i . 'nid'} = $entity->field_choose_a_package['und'][$i]['target_id'];
${'package' . $i} = node_load(${'package' . $i . 'nid'});
$packagestotal += ${'package' . $i}->field_price['und'][0]['value'];
}
}
$entity_field[0]['value'] = $packagestotal;
That should work.
Although, I would recommend that you wrap the package variables in an array rather than using variable variables as then the code would be much more readable and you could access each package attribute using $package[$i]
First of all I'm wondering if this is even possible in Laravel?
I have this code:
$master_array = $_POST['master_search_array'];
$count = count($master_array);
$master_string = '';
for($i=0; $i<$count; $i++) {
if($master_array[$i] == "Dining"){
$master_string .= "where('dining', 'dining')";
}
if($master_array[$i] == "Party"){
$master_string .= "where('party','party')";
}
....ETC you get the point
}
$tours = DB::table('tours')->$master_string->get();
return $tours;
So at the end I should get something like this:
$tours = DB::table('tours')->where('dining', 'dining)->where('party','party')->get();
How can I do this in laravel, it gives me an error, no matter if I pass it as $master_string or {{$master_string}}.
There is no need for master string. Just use the query builder how it's meant to be used...
$master_array = $_POST['master_search_array'];
$count = count($master_array);
$query = DB::table('tours');
for($i=0; $i<$count; $i++) {
if($master_array[$i] == "Dining"){
$query->where('dining', 'dining');
}
if($master_array[$i] == "Party"){
$query->where('party', 'party');
}
}
$tours = $query->get();
return $tours;
Use the ability to add wheres to the query along the way.
DB::table('tour')->where(function($query) use ($master_array)
{
foreach($master_array as $k => $v) {
if($v == "Dining"){
$query->where('dining','dining');
}
if($v == "Party"){
$query->where('party','party');
}
}
})
->get();
I want to put the input like "RKKRRRRK" and try to get the output like largest continuous segment.. Suppose my input may be "RKKKR" then my program will display 'KKK' is the largest continuous segment.. and then it also display the count is 3..
I've already write the code for counting 'R' values.. now i want this program also... need help anyone help me.. thanks in advance.
Here the code:-
<?php
function numberOfR($string1)
{
for($i=0;$i <strlen($string1);$i++)
{
if($string1[$i]!='K')
{
$count++;
}
}
return $count;
}
$return_value= numberOfR("RKKRK");
echo "R's count is:";
echo $return_value;
?>
<?php
function getLongetSegment($string) {
$currentSegmentChar='';
$currentSegment="";
$biggestSegment="";
$current_length=0;
$biggest_length=0;
for($i=0;$i<strlen($string);$i++) {
$char = $string[$i];
if($char != $currentSegmentChar || $currentSegmentChar == '') {
if($current_length >= $biggest_length) {
$biggestSegment = $currentSegment;
$biggest_length = $current_length;
}
$currentSegmentChar = $char;
$currentSegment = $char;
$current_length = 1;
}
elseif($currentSegmentChar != '') {
$currentSegment .= $char;
$current_length++;
}
}
if($current_length >= $biggest_length) {
$biggestSegment = $currentSegment;
}
return array("string" => $biggestSegment,"length" => $biggest_length);
}
print_r(getLongetSegment("RKKRGGG"));
?>
Result: GGG
You can use preg_match_all over here as
preg_match_all('/(.)\1+/i','RKKRRRRK',$res);
usort($res[0],function($a,$b){
return strlen($b) - strlen($a);
});
echo $res[0][0];
Not sure if I understood this quite right. Something like this:
function maxCharSequece($string1)
{
$maxSeq = $seq = 0;
$maxChar = $lastChar = null;
for( $i = 0; $i < strlen($string1); $i++ )
{
$c = $string1[$i];
if (!$lastChar) $lastChar = $c;
if ( $lastChar == $c ){
if ( ++$seq > $maxSeq ) $maxChar = $lastChar;
}
else {
$maxSeq = $seq;
$seq = 0;
}
}
return $maxChar;
}
You can use preg_replace_callback to receive all continuous segments and select the longest
$sq = '';
preg_replace_callback('/(.)\1+/',
function ($i) use (&$sq) {
if(strlen($i[0]) > strlen($sq)) $sq = $i[0];
}, $str);
echo $sq . " " . strlen($sq);
I made this code for calculating max winning & losing streaks on an array of values. But I can get my head around doing it in one foreach loop. Currently I'm using 2 loops as follow :
public function calculateStreaks()
{
$max_win_streak = 0;
$_win_streak = 0;
$max_loss_streak = 0;
$_loss_streak = 0;
foreach($this->all_trades_pnl as $value){
if($value >= 0) {
$_win_streak++;
if($_win_streak > $max_win_streak){
$max_win_streak = $_win_streak;
}
}
else {
$_win_streak = 0;
}
}
foreach($this->all_trades_pnl as $value){
if($value < 0) {
$_loss_streak++;
if($_loss_streak > $max_loss_streak) {
$max_loss_streak = $_loss_streak;
}
}
else {
$_loss_streak = 0;
}
}
return array('win_streak' => $max_win_streak, 'loss_streak' => $max_loss_streak);
}
It works but seems far from optimized, any ideas to code this better ?
Thanks a lot in advance,
Regards,
John
Since both your loop are equal i think you can mix them toghter and assign all variables at once as follow
public function calculateStreaks()
{
$max_win_streak = 0;
$_win_streak = 0;
$max_loss_streak = 0;
$_loss_streak = 0;
foreach($this->all_trades_pnl as $value){
if($value >= 0) {
$_win_streak++;
if($_win_streak > $max_win_streak){
$max_win_streak = $_win_streak;
}
$_loss_streak = 0;
}
else if($value < 0) {
$_loss_streak++;
if($_loss_streak > $max_loss_streak) {
$max_loss_streak = $_loss_streak;
}
$_win_streak = 0;
}
}
return array('win_streak' => $max_win_streak, 'loss_streak' => $max_loss_streak);
}