Check if a value is present in a comma separated varchar string - laravel

I have a record "id_zone" in database that store cites id like this $abilitato->id_zone = '1, 2, 3, 9, 50'
From laravel i need to check if a value passed from url is present in this field. The following work only if i have a single value
$abilitato = \App\Models\Servizi::where('id', $servizio)->('id_zone', $verifica->id_citta)->first();
if(!empty($abilitato) && empty($verifica->multicap)) {
$json = ['CAP' => '1' , 'DEB' => $cap ];
}else{
$json = ['CAP' => '0' , 'DEB' => $cap];
}
i need to check if

If you want to know if a value is in your array you can use this functiĆ³n to know it.
here is a example:
// First convert your string to array
$myString = $abilitato->id_zone; // Here your string separate with comas
$array = explode(',', $myString); // Here convert it to array
$value = 7; // Here you put the value that you want to check if is in array
// Check if exist a value in array
if (in_array($value, $array)){
echo "Exist in array";
}else{
echo "No exist in array";
}
This is the documentation of these functions: explode , in_array
Regards!

Related

check data that is not in array with 2 value matches

I have 2 arrays and I want to check those arrays with 2 value matches,
if those 2 value not matches I want to insert into database.
Code I have tried :
$data1 = {['reg_no'=>123,'name'=>'John'],['reg_no'=>1234,'name'=>'Lisa']};
$data2 = {['reg_no'=>123,'name'=>'John'],['reg_no'=>1234,'name'=>'Lisa'],['reg_no'=>12345,'name'=>'Roger']};
foreach($data1 as $d1)
foreach($data2 as $d2)
if($d1['reg_no'] != $d2['reg_no'] && $d1['name'] != $d2['name'])
//insert into database
// this not work because it will enter all data that not match
endif
endforeach
endforeach
you can use FirstOrNew Or FirstOrCreate in laravel.
like insert if not exist
$students = User::firstOrNew(['student_id' => $request->student_id, 'course_code' => $request->course_code]);
$students->foo = $request->foo;
$students->save();
$data1 = {['reg_no'=>123,'name'=>'John'],['reg_no'=>1234,'name'=>'Lisa']};
$data2 = {['reg_no'=>123,'name'=>'John'],['reg_no'=>1234,'name'=>'Lisa'],['reg_no'=>12345,'name'=>'Roger']};
$data = array_uintersect($data1, $data2, "strcasecmp");
if($data['reg_no'] != $data1['reg_no'] && $data2['reg_no']) {
// insert
}

Count number of same values in JSON array and convert it to string

My JSON looks something like this:
[
{"pet_type":"Dog","weight":"26","description":"Akita"},
{"pet_type":"Dog","weight":"6","description":"Pug"},
{"pet_type":"Cat","weight":"4","description":"Manx"},
{"pet_type":"Dog","weight":"12","description":"Beagle"},
{"pet_type":"Cat","weight":"5","description":"Siberian"}
]
How could I convert it to a string which would look like3 Dogs, 2 Cats?
The way I tried is filling an array with pet_type and than use array_count_values to count number of same records, and later I go through that array in a foreach and concat string like this:
foreach ($count_animals as $type => $number) {
$animals .= $number.' '.str_plural($type, $number).', ';
}
This works, but my question is, could I do it with less code, directly from JSON, without using one more foreach loop?
If it works, you can keep your code.
If you want less code, you can use this version :
$json = '[
{"pet_type":"Dog","weight":"26","description":"Akita"},
{"pet_type":"Dog","weight":"6","description":"Pug"},
{"pet_type":"Cat","weight":"4","description":"Manx"},
{"pet_type":"Dog","weight":"12","description":"Beagle"},
{"pet_type":"Cat","weight":"5","description":"Siberian"}
]';
print_r(array_count_values(array_map(function($item) {
return $item['pet_type'];
}, json_decode($json, true))));
Gonna display :
Array ( [Dog] => 3 [Cat] => 2 )
in your controller
$pet = Pet::get();
$petcount = Pet::where('pet_type','Dog')->get();
In your blade
<h1>{{count($petcount)}} Dog</h1>

create method in store function stores array value in db

$array = array($t, $c, $s);
foreach ($array as $a) {
receipt::create($a);
}
i want to pass the array content to database but i got this error
"Type error: Argument 1 passed to Illuminate\Database\Eloquent\Builder::create() must be of the type array, string given,
Actually while insert we should provide the array data even single field or more no of fields.
For example two fields : receipt::create($a). In this $a should contain two values in array format.
New example updated below as per your request. In this your $a variable should be like below format
$a = array(
'user_id' => $userId,
'receipt_description' => $desc
);
$receiptId = receipt::create($a)->id;

Cakephp 3 How to make session array

I am trying to write session in controller. My structure is
$_SESSION['a'][0] = 1;
$_SESSION['a'][1] = 2;
$_SESSION['a'][2] = 3;
And I am trying this
Configure::write('Session', ['a' =>'1'])
But it is not working. How do this in cakephp 3 way
To write variable in Session in CakePHP 3 you need to write following code :
$this->request->session()->write('Your Key',Your_array);
To know more information you can visit here :
http://book.cakephp.org/3.0/en/development/sessions.html
To make things perfectly clear:
// code writing array to session
$a = [ "abc" => "word", "123" => 42, "?" => $b ];
$a["more"] = "if you need to add";
$a[] = "whatever";
$this->request->session()->write( 'my_array', $a );
// code reading array from session
$recall = $this->request->session()->read( 'my_array' );
debug( sprintf( "What's the word? [%s]", $recall["abc"] ) );
You can simply use
$session->write([
'key1' => 'blue',
'key2' => 'green',
]);
I am refering to
http://book.cakephp.org/3.0/en/development/sessions.html#reading-writing-session-data
The answer is that this cannot be done in CakePHP 3.x
In vanilla PHP, it's possible to do this:
<?php
session_start();
$_SESSION['a'][0] = 1;
$_SESSION['a'][1] = 2;
$_SESSION['a'][2] = 3;
var_dump($_SESSION);
?>
Which will output:
array(1) {
["a"]=> array(3) {
[0]=> int(1)
[1]=> int(2)
[2]=> int(3)
}
}
This is correct, and what should happen.
In CakePHP, you cannot specify arrays in the session key. For example:
$this->request->session()->write('a[]', 1);
$this->request->session()->write('a[]', 2);
$this->request->session()->write('a[]', 3);
Will not work.
If you remove the [] the value will get overwritten. For example:
$this->request->session()->write('a', 1);
$this->request->session()->write('a', 2);
$this->request->session()->write('a', 3);
The value of $this->request->session()->read('a') would be 3. The values 1 and 2 have been overwritten. Again, this is to be expected because you're overwriting the key a each time. The equivalent vanilla PHP for this is:
$_SESSION['a'] = 1;
$_SESSION['a'] = 2;
$_SESSION['a'] = 3;
Due to the lack of an indexed array, $_SESSION['a'] gets overwritten each time. This is normal behaviour. It needs to have the indexes (e.g. ['a'][0], ['a'][1], ...) to work!
The other answers where they have given things like key1 and key2 are not appropriate. Because there are many situations where you want everything contained within an indexed array. Generating separate key names is wrong for this type of scenario.
My edit of the accepted answer was rejected, so I present the - seemingly necessary - explicit code example, for the benefit of #Andy and others.
// code to write to session
$a = [ 0 => "zero", 1 => "one", 2 => "two" ];
$a[] = "three";
$this->request->session()->write( 'my_array', $a );
// code to read from session
$z = $this->request->session()->read( 'my_array' );
debug( $a[3] ); // outputs "three"

Make unique invoice numbers with mysql and use

At the moment this is my function to create a random unique invoice number which is stored in a form's hidden field
function generate_invoice_number() {
global $wpdb;
$lastVisitor = $wpdb->get_results("SELECT visitorID FROM event_visitors_2014 ORDER BY visitorsID DESC LIMIT 1", ARRAY_A);
$nr_last = $lastVisitor[0]['visitorID'];
$nr = 501 + $nr_last;
$value = sprintf( '%04d', $nr );
$number = 'LEDEXPO'.date('Y').'-'.uniqid().'-'.$value;
return $number;
}
I have a problem when multiple people are using the form at the same time, say 3 people are using the form they all have the same number generate.
So i added uniqid(), so $value could be duplicated but $number should be unique? Is this correct or is there a better way?
How can i make test function to test this function on uniqueness?
regards
Try This:
function generate_invoice_number()
{
global $wpdb;
$lastVisitor = $wpdb->get_results("SELECT visitorID FROM event_visitors_2014 ORDER BY visitorsID DESC LIMIT 1", ARRAY_A);
$nr_last = $lastVisitor[0]['visitorID'] + 1;
$number = date('Ymd') . $nr_last;
return $number;
}

Resources