Custom query for database in Laravel - php

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();

Related

Detecting a cycle in an array PHP

I'm running a simple script which puts an integer through the formula of the Collatz conjecture and adds the output of each step into an array.
I want to use a function to detect if there's a cycle in the array, using Floyd's algorithm. And though I feel like I'm not doing a bad job, I don't seem to get it right. At this moment I'm getting the error Trying to get property 'next' of non-object in C:\xampp\htdocs\educom\week3\functions.php on line 12
See my code below. Any feedback is greatly appreciated!
include("functions.php");
$n = $_POST['number'];
$step = 0;
$reeks1 = array();
$cycle = 0;
echo "Your entry is: ". $n ."<br><br>";
while($n!==1 && $cycle==0){
$cycle = detect_cycle(array($reeks1));
if($n % 2 == 0){
$n = $n / 2;
array_push($reeks1, "$n");
$step++;
echo $step .": ". $n ."<br>";
}else{
$n = ($n * 3) + 1;
array_push($reeks1, "$n");
$step++;
echo $step .": ". $n ."<br>";
}
}
functions.php:
function detect_cycle($node){
if ($node==NULL){
return FALSE;
}
$turtle = $node;
$rabbit = $node->next;
while($rabbit != NULL){
if($rabbit === $turtle){
return TRUE;
}elseif($rabbit->next == NULL){
return FALSE;
}else{
$turtle = $turtle->next;
$rabbit = $rabbit->next->next;
}
}
return FALSE;
}
Check this out. IMPORTANT I don't know is this according to your theory. but it won't give you errors if you use like this.
function detect_cycle($node){
if ($node==NULL){
return FALSE;
}
$turtle = $node;
$rabbit = $node[0];
while($rabbit != NULL){
if($rabbit === $turtle){
return TRUE;
}elseif($rabbit[0] == NULL){
return FALSE;
}else{
$turtle = $turtle[0]; // use the number of the element key starting from 0
$rabbit = $rabbit[0][1];
}
}
return FALSE;
}

Tips for optimising this PHP code

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])));
}
}

How to use regular expression in the WHERE clause of query in Laravel?

I have a table named "Shows". There is a column "show_date". I want to retrieve the shows whose show_date is todays date.
Following is my query
$s = DB::table('shows')->get();
$a = DB::table('shows')->select('show_date')->get();
foreach ($s as $key => $value)
{
$date_test = date('Y-m-d');
$s_test = DB::table('shows')->where('show_date',preg_grep('/"'.$value->show_date.'"./', $a->show_date))->get();
echo "<pre>"; var_dump($s_test);
if(explode(" ",$value->show_date)[0] == date('Y-m-d'))
{
$shows1 = DB::table('shows')->where('id',$value->id)->get();
$s1 = DB::table('transactions')
->select(DB::raw("GROUP_CONCAT(selected_seats SEPARATOR '') as selected_seats"),'userid','amount','show_id')
->where("show_id","=",$value->id)
->groupBy('userid')
->groupBy('amount')
->orderBy('userid','ASC')
->orderBy('amount', 'DESC')
->get();
if($s1 != null)
{
echo $value->id;
$c = count($s1);
$sub_count1 = 0; $next_id = ""; $total_array = 0;
for($i=0;$i<$c;$i++)
{
$first_character = $s1[$i]->selected_seats;
$sub_count = substr_count($s1[$i]->selected_seats, ',');
$sub_count1 = $sub_count1 + $sub_count;//to get the total no. of seats
for($j=0,$k=0;$j<$sub_count;$j++,$k++)
{
// split the string with comma.
$s = explode(',',$first_character);
// get total no. of seat names listed in one row in table.eg A 1,B 2. Then $sub_count would be 2
$p = $s[$j][0];
}
}
// get seats for each show from transaction table.
$demo = DB::table('theater_setting')->select('row_seats_selling_price','row')->where('show_id',$value->id)->get();
foreach ($demo as $key => $val) {
$categoryArr[$val->row]=$val->row_seats_selling_price;
}
$demo4 = DB::table('theater_setting')->select('row_seats_selling_price','row')->where('show_id',$value->id)->get();
$demo3 = DB::table('transactions')->where('show_id',$value->id)->select('selected_seats','userid')->get();
for($p=0;$p<count($demo3);$p++)
{
$arr = explode(',', substr($demo3[$p]->selected_seats,0,-1));
$trans[] = $demo3[$p]->userid;
foreach ($arr as $k => $v)
{
$seats[$demo3[$p]->userid][]=$v;
}
}
foreach ($seats as $user_id=>$v)
{
for ($h=0; $h < count($v); $h++)
{
$e = explode(" ", $v[$h]);
$p = $e[0];
$demo_array[$p][$user_id][] = $v[$h];
}
$users = DB::table('users')->where('id',$user_id)->get();
}
return view('Backend.NewReportByShowsCategory2')->with([
's1'=>$s1,'shows1'=>$shows1,'demo'=>$demo,'categoryArr'=>$categoryArr,'demo3'=>$demo3,'demo4'=>$demo4,'demo_array'=>$demo_array]);
}
else
{
return view('Backend.NewReportByShowsCategory2')->with([
's1'=>$s1]);
}
}
}
I am getting the following error:
Object of class stdClass could not be converted to string
There is alternative way:
DB::table('shows')->where('show_date', 'REGEXP', Carbon\Carbon::now()->toDateString())->get();
You could convert show_date to a DATE and compare it with the current date -
$s_test = DB::table('shows')->whereRaw('DATE(show_date)=CURRENT_DATE')->get()
However, here's the regex query for selecting rows with a particular date (the current date in this case),
DB::table('shows')->whereRaw("show_date REGEXP '". Carbon\Carbon::now()->toDateString() . "'")->get()

Is there anyway to repeat the biggest segment of continuous segment of repeat using php?

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);

Re-inserting the same data into a 2D array until the array reaches a certain number of entries

I have a simple foreach loop which enters data in a 2D array:
foreach ($query as $row){
if (!isset($sites[$row->site])){ $sites[$row->site] = array(); }
if (!isset($sites2[$row->site])){ $sites2[$row->site] = array(); }
if ($row->type == 1){
$sites[$row->site][] = array($row->data1, $row->data2);
} else {
$sites2[$row->site][] = array($row->data1, $row->data2);
}
}
I need a minimum of 20 entries in the array's ($sites and $sites2).
So if the query has lets say 5 rows, I want to reiterate the loop, repeating the 5 existent rows (inserting them inside the arrays) until the arrays reach 20 rows.
Any ideas?
try this:
$rows=0;
$haveDuplicated=false;
while($rows<20){
foreach ($query as $row){
if (!isset($sites[$row->site])){ $sites[$row->site] = array(); }
if (!isset($sites2[$row->site])){ $sites2[$row->site] = array(); }
if ($row->type == 1){
$sites[$row->site][] = array($row->data1, $row->data2);
} else {
$sites2[$row->site][] = array($row->data1, $row->data2);
}
$rows++;
if ($rows>=20 && $haveDuplicated) break;
}
$haveDuplicated=true;
}
I suppose you didn't see array_pad() yet?
Edit: Re-reading your question, I don't think this function is helpful, at least not by itself.
I'm quite tired today, and I can't concentrate much, so can you please do me the favour of showing us the expected results as opposed to your faulty(no offence) code?
$index = 0;
for ($i=0; $i < 20; $i++) {
if($index >= count($query))
$index = 0;
if (!isset($sites[$query[$index]->site])){ $sites[$query[$index]->site] = array(); }
if (!isset($sites2[$query[$index]->site])){ $sites2[$query[$index]->site] = array(); }
if ($query[$index]->type == 1){
$sites[$query[$index]->site][] = array($query[$index]->data1, $query[$index]->data2);
} else {
$sites2[$query[$index]->site][] = array($query[$index]->data1, $query[$index]->data2);
}
$index++;
}
This will work at all:
$row = 1;
while($row == 20){
foreach ($query as $row){
if (!isset($sites[$row->site])){ $sites[$row->site] = array(); }
if (!isset($sites2[$row->site])){ $sites2[$row->site] = array(); }
if ($row->type == 1){
$sites[$row->site][] = array($row->data1, $row->data2);
} else {
$sites2[$row->site][] = array($row->data1, $row->data2);
$row++;
}
}

Categories