PHP - Days of the Week by Array - arrays

Here is my code:
$day = 1;
$dayList = array("0"=>"Sunday","1"=>"Monday");
if(in_array($day,$dayList)) {
echo $dayList[$day];
}
I tried $day = 0, and it works good, but it doesn't work if string is 1.
How can I solve this problem?

in_array() checks values, not keys. So in this instance it won't do what you want. isset() is the function you need to use, try this:
if (isset($dayList[$day])) {
...
}

Use array_key_exists :
$day = 1;
$dayList = array("0"=>"Sunday","1"=>"Monday");
if(array_key_exists($day,$dayList)) {
echo $dayList[$day];
}
More info:
http://php.net/manual/en/function.array-key-exists.php
Another method:
You could create a function that returns this value or the key like so:
function getDayOfTheWeek($name)
{
$dayList = array("0"=>"Sunday","1"=>"Monday","2"=>"Tuesday","3" => "Wednesday");
// if a string make sure it's capitalized
if (preg_match('/[^A-Za-z]/', $name)) {
$name = ucwords(strtolower($name));
} else {
// if not a string flip the array and get name
$dayList = array_flip($dayList);
}
return $dayList[$name];
}
// print results for each call to function
var_dump(getDayOfTheWeek('0')); // returns Sunday
var_dump(getDayOfTheWeek('1')); // returns Monday
var_dump(getDayOfTheWeek('Monday')); //returns 1
var_dump(getDayOfTheWeek('Tuesday')); // returns 2

Related

Symfony - saving array to database

I wrote a function where I get array of marks that i need to post to my database..
My function stores it in a filed row like:
And I need to pull just one per column individually like:
Here is my api call..
public function generate(Map $seatMap)
{
$layout = $seatMap->getSeatLayout();
$seats = [];
$layoutArray = json_decode($layout, true);
$columns = range('A', 'Z');
foreach($layoutArray as $index => $result)
{
$columnLetter = $columns[$index];
$letters = str_split($result);
$letterIndex = 1;
foreach($letters as $letterIndex => $letter) {
switch($letter) {
case 'e':
$seats[] = $columnLetter . $letterIndex;
$letterIndex++;
}
}
}
foreach($seats as $seat => $result) {
$result = new Seat();
$result->setName(json_encode($seats));
$this->em->persist($result);
$this->em->flush();
}
}
Any suggestions?
I think that problem is in the part where I need to store it to database..
If I understand you correctly, your issue is here:
foreach($seats as $seat => $result) {
$result = new Seat();
$result->setName(json_encode($seats));
$this->em->persist($result);
$this->em->flush();
}
}
You're indeed creating new Seat instance for every seat, but in this line:
$result->setName(json_encode($seats));
you still assign all (encoded) seats to every instance of Seat. What you want is to assign only the seat from current loop iteration, which is represented by $result variable.
So try with:
$result->setName($result);
You do not need json_encode here too.
If your array is like you say it it then try this
foreach($seats as $seat) {
$result = new Seat();
$result->setName($seat);
$this->em->persist($result);
$this->em->flush();
}

Multiple collections in an array (session variable) — Property does not exist

I'am trying to fetch a session variable if the user is a guest. The variable is called "cart" and is set like this:
$product = new Collection((object) [
'product_id' => $request->pId,
'amount' => $request->amount,
'variations' => $variations
]);
Session::push('cart', $product);
Then I later fetch it:
if(Auth::check()){
$cartProducts = ShoppingCartItem::where('user_id', '=', Auth::user()->id)->get();
}else{
$cartProducts = Session::get('cart');
}
foreach($cartProducts as $product){
dd($product);
$totalAmount += $product->amount;
$totalPrice += (PriceHelper::getProductPrice($product->product->id, $product->amount));
}
The problem here is that dd($product) still outputs an array (the session variable array I assume) which means that for example $product->amount does not exist.
This is the output from dd($product):
You can either access the values using get():
foreach ($cartProducts as $product) {
$totalAmount += $product->get('amount');
$totalPrice += PriceHelper::getProductPrice($product->get('product_id'), $product->get('amount'));
}
or as an array:
foreach ($cartProducts as $product) {
$totalAmount += $product['amount'];
$totalPrice += PriceHelper::getProductPrice($product['product_id'], $product['amount']);
}
or you could use sum() on the collection instead of using foreach:
$cartProducts = collect(Session::get('cart'));
$totalAmount = $cartProducts->sum('amount');
$totalPrice = $cartProducts->sum(function ($product) {
return PriceHelper::getProductPrice($product['product_id'], $product['amount']);
});
Edit
For a quick fix if you need $product to be an object you could do something like:
$cartProducts = collect(Session::get('cart'))->map(function ($item) {
return (object)$item->toArray();
});
Hope this helps!

Count result array to string conversion error in codeigniter

I am using this method in my model to get a count result from my database:
function members($group_id)
{
$this->db->where('group_id',$group_id);
$query = $this->db->query('SELECT COUNT(group_id) FROM member');
return $query;
}
And in my controller there is this method:
function total_members ()
{
$group_id = $this->input->post('group_id');
$this->load->model('Member_model');
$members = $this->Member_model->members($group_id);
echo $members;
}
And am getting this weird error which says:
Severity: 4096
Message: Object of class CI_DB_mysqli_result could not be converted to string
Filename: controllers/Payment.php
You need to return a result set which requires another call. In this case I suggest row(). Try these revised functions.
function members($group_id)
{
$this->db->where('group_id', $group_id);
$query = $this->db->query('SELECT COUNT(group_id) as count FROM member');
return $query->row();
}
function total_members()
{
$group_id = $this->input->post('group_id');
$this->load->model('Member_model');
$members = $this->Member_model->members($group_id);
if(isset($members))
{
echo $members->count;
}
}
Learn about the different kinds of result sets here
Try this
Model
function members($group_id) {
return $this->db->get_where('member', array('group_id' => $group_id))->num_rows();
}
Controller
function total_members() {
$group_id = $this->input->post('group_id');
$this->load->model('member_model');
$members = $this->member_model->members($group_id);
print_r($members);
}
In codeigniter there is num_rows() to count the rows. For more information check the documentation .

PHP uksort function using global variable fails after PHP upgrade to 5.3.3

I have a user defined sort function which uses a 'global' declaration in order to refer to a multi-dimensional array when deciding on the correct sort order. It used to work fine under PHP 5.1.6 but now fails under 5.3.3.
The code throws PHP warning:
PHP Warning: uksort(): Array was modified by the user comparison function
But the code definitely does not modify the array.
This code duplicates the problem:
$arr = array();
$arr['i1']['val1'] = 99;
$arr['i1']['val2'] = 100;
$arr['i2']['val1'] = 89;
$arr['i2']['val2'] = 101;
function cmp($a, $b)
{
global $arr;
if ($arr[$a]['val2'] > $arr[$b]['val2']) { return 1; }
if ($arr[$a]['val2'] < $arr[$b]['val2']) { return -1; }
return 0;
}
if (uksort($arr, 'cmp'))
{
echo "success";
}
else
{
echo "failure";
}
If you're not going to sort by the actual keys, don't use uksort but usort or uasort:
function cmp($a, $b) {
return $a['val2'] - $b['val2'];
}
uasort($arr, 'cmp');
As sidestepping the issue is so popular, here is the cause of your issue:
global $arr;
I'm sure you sensed that aready, to solve that, remove the line and replace $arr with $GLOBALS['arr']. This removes the modification message and you'er accessing the global variable from the symbol table and not the one uksort is currently operating on.
Example:
<?php
$arr = array();
$arr['i1']['val1'] = 99;
$arr['i1']['val2'] = 100;
$arr['i2']['val1'] = 89;
$arr['i2']['val2'] = 101;
function cmp($a, $b)
{
if ($GLOBALS['arr'][$a]['val2'] > $GLOBALS['arr'][$b]['val2']) { return 1; }
if ($GLOBALS['arr'][$q]['val2'] < $GLOBALS['arr'][$b]['val2']) { return -1; }
return 0;
}
if (uksort($arr, 'cmp'))
{
echo "success\n";
}
else
{
echo "failure\n";
}
print_r($arr);
Output for 5.3.23 - 5.5.3: (other versions crash/misbehave)
success
Array
(
[i1] => Array
(
[val1] => 99
[val2] => 100
)
[i2] => Array
(
[val1] => 89
[val2] => 101
)
)
Ups, maybe that's why you see a warning in more recent versions: (Demo: http://3v4l.org/DkK3v)

how to check the value of an array in codeigniter

$result=array();
$count = count($days);
for($i=0;$i<$count-1; $i++)
{
$bookDate = $days[$i];
$fromDate = $this->booking_model->Get_BookedDate($bookDate,$roomname);
if ($fromDate != 0)
{
$result[] = $bookDate;
}
}
return $result;
This is my codeigniter controller function here I want to check the value of $fromDate is zero or not. I am getting the array like this
Array ( [0] => Array ( ["2013-04-27" between fromDate and toDate] => 1 ) )
I am very new to codeigniter. Thank you for any help.
$result=array();
$count = count($days);
for($i=0;$i<$count-1; $i++)
{
$bookDate = $days[$i];
$fromDate = $this->booking_model->Get_BookedDate($bookDate,$roomname);
if (!empty($fromDate[0]['"'.$bookDate.'" between fromDate and toDate']))
{
$result[] =$bookDate;
}
}
return $result;
Try this.IT may help you
Make use of empty() function.
if(!empty($fromdate)) { //if $formdate is empty or 0 or false the loop won't be executed
//Your code.
}
if (!empty($fromDate))
{
$result[] = $bookDate;
}
Try this.

Resources