I have something like this:
function odeon(){
$data= file_get_contents('https://api.cinelist.co.uk/get/times/cinema/10565');
$data = json_decode($data);
$id = 1;
foreach($data->listings as $listing){
$title = $listing->title;
$time = implode(', ', $listing->times);
$business_id = 1;
$film = Film::where('id', $id)->first();
$id = $id + 1;
// if news is null
if (!$film) {
$film = new Film();
}
$film->title = $title;
$film->times = $time;
$film->business_id = $business_id;
$film->save();
}
return view('odeon')->with(['listings' => $data->listings]);
}
What I want to do is add more cinemas so instead of:
$data=
file_get_contents('https://api.cinelist.co.uk/get/times/cinema/10565');
$data= file_get_contents('https://api.cinelist.co.uk/get/times/cinema/6756');
Be something like:
$data= file_get_contents('https://api.cinelist.co.uk/get/times/cinema/6756-10565');
So to go throught from numbers 6756 to 10565, problem is this as well as each cinema has a different business_id I don't want to replicate function for each cinema so any help will be appreciated ;)
Another issue is what if another day therewill be less films than previous day, of course I don't want to display yesturdays films for today
//edit
Ok I will do my best to explain what I want to achieve.
I want to loop throught a cinema, retrieve films for today, save into database, retrieve data for tomorrow save into database, etc. I want to do it for 7 days, Now for each cinema, cinema id + date changes:
https://api.cinelist.co.uk/get/times/cinema/10565?day=2017-06-14
Would bring me back films for today, but I want to achieve it for 7 days so something like this:
$cinema_id=['10', '20'] (number = cinema_id)
$startdate = strtotime("today");
$enddate = strtotime("+7 Days");
while ($startdate < $enddate) {
echo date("Y-m-d", $startdate) . "<br>";
$startdate = strtotime("+1 Days", $startdate);
}
$data= file_get_contents (https://api.cinelist.co.uk/get/times/cinema/$cinema_id?day=$startdate)
So basically I want to loop throught array of cinema and for each cinema_id, go throught 7 days ahead and save details to database. Of course I don't want to keep old records, so each day they either have to be removed or updated
Your question is vague but probably you mean this...
function odeon(){
$arrayOfCinemaIds = [10565,6756];
foreach($arrayOfCinemaIds as $id){
//append your id
$data= file_get_contents('https://api.cinelist.co.uk/get/times/cinema/'.$id);
$data = json_decode($data);
$id = 1;
foreach($data->listings as $listing){
$title = $listing->title;
$time = implode(', ', $listing->times);
$business_id = 1;
$film = Film::where('id', $id)->first();
$id = $id + 1;
// if news is null
if (!$film) {
$film = new Film();
}
$film->title = $title;
$film->times = $time;
$film->business_id = $business_id;
$film->save();
}
$listings[]=$data->listings;
}
//$listings will have all the listings from all the loops
return view('odeon')->with(['listings' => $listings]);
}
You will just need to add more entries to $arrayOfCimenaIds as you need. Typically you would load them up from a Db or other data store.
EDIT:
If you have a sequence of numbers you dont need the array you can do
for($id=6756;$id<=10565;$id++){..}
instead of the foreach()
Related
Just a quick question guys really thankful for everyone who can help.
How do I foreach loop inside create eloquent in laravel
Here is my code. I'm trying to get and match the answers for their respective survey questions
public function answer_survey(Request $request, $id)
{
$userId = Auth::user()->id;
$user = User::where('id', $userId)->first();
$userNectarPoint = UserNectarPoint::where('user_id', $userId)->first();
$survey = Survey::find($id);
$survey_questions = SurveyQuestion::where('survey_id', $survey->id)->get();
$current_nectarpt_value = $userNectarPoint->nectar_points;
$questionIds = $request->id;
$questions = $request->question;
$answers = $request->answer;
foreach ($answers as $answer) {
}
foreach ($survey_questions as $survey_question) {
$userAnsweredSurvey = new UserAnsweredSurvey;
$userAnsweredSurvey->user_id = $userId;
$userAnsweredSurvey->user_fullname = $user->first_name . ' ' . $user->middle_initial . ' ' . $user->family_name;
$userAnsweredSurvey->survey_id = $survey->id;
$userAnsweredSurvey->survey_title = $survey->title;
$userAnsweredSurvey->survey_question_id = $survey_question->id;
$userAnsweredSurvey->survey_question = $survey_question->question;
$userAnsweredSurvey->answer = $answer;
$userAnsweredSurvey->save();
}
$result_nectarpt = $current_nectarpt_value + $survey->reward_points;
$userNectarPoint->nectar_points = $result_nectarpt;
$userNectarPoint->save();
return back()->with('status', 'survey_done');
}
I'm trying to create a sort function where if it's selected it will display the necessary amount of orders. For example if the user selects to display orders from the last 3 months then that needs to be displayed.
The problem I'm having is that nothing is being shown when I dd($three_months)
public function trackOrders()
{
$menus_child = Menu::where('menu_id', 0)->with('menusP')->get();
$contacts = Contact::all();
$orders = Auth::user()->orders->sortByDesc('order_date');
$orders->transform(function($order, $key){
$order->cart = unserialize($order->cart);
return $order;
});
$from = Carbon::now('+2:00');
$to = $from->copy()->subMonth(3);
$three_months = Order::whereBetween('created_at', [$from, $to])->get();
dd($three_months);
return view('public.users.track-orders', compact('menus_child', 'contacts', 'orders', 'order_item'));
}
but when I do dd($three_months) nothing shows up. I only get
Collection {#320 ▼
#items: []
}
Order matters when using SQL's BETWEEN. Your $from value is greater than your $to value. So try swapping them around:
$to = Carbon::now('+2:00');
$from = $from->copy()->subMonth(3);
$three_months = Order::whereBetween('created_at', [$from, $to])->get();
Maybe it's because you are not Formatting DateTime
$from = Carbon::now('+2:00')->format('Y-m-d H:i:s');
$to = $from->copy()->subMonth(3)->format('Y-m-d H:i:s');
Try This code.
Edit: You cant Use copy() method on string. so you can do.
$to = Carbon::now('+2:00')->subMonth(3)->format('Y-m-d H:i:s');
I am getting cinema title + times using API from Cinelist, I then want to save these values into a database.
At the moment, it does save but only 1 record, the last one. However, I want it to save each one.
Also each time it is run I want to update existing records instead of creating new ones unless there are more results.
So usually there are 5 records, each time I run the function I want to update the database with the new 5 records, however, if it's a different day and there are 6 records I want to update 5 records and insert 1 extra one so there is 6.
My code so far:
function odeon(){
$data= file_get_contents('https://api.cinelist.co.uk/get/times/cinema/10565');
$data = json_decode($data);
foreach($data->listings as $listing){
$title = $listing->title;
$time = implode(', ', $listing->times);
$id = + 1;
$films = Film::where('id', $id)->first();
if (!$films) {
$films = new Film();
}
$films->title = $title;
$films->times = $time;
$films->save();
}
}
You may use eloquent's updateOrCreate method to insert non-existent data and update existing data.
function odeon(){
$data= file_get_contents('https://api.cinelist.co.uk/get/times/cinema/10565');
$data = json_decode($data);
foreach($data->listings as $listing){
$title = $listing->title;
$time = implode(', ', $listing->times);
Films::updateOrCreate([
'title' => $title,
'$times' => $time
]);
}
}
I have build my own component in joomla and client wants now a friendly urls f.e
website.com/someplace/{product-id}-{product-name}. So i Build my own router like this.
function componentBuildRoute(&$query)
{
$segments = [];
if (isset($query['view'])) {
$segments[] = "szkolenie";
unset($query['view']);
}
if (isset($query['product_id'])) {
$productName = JFilterOutput::stringURLSafe(strtolower(getProductName($query['product_id'])));
$newName = $query['product_id'] . '-' . $productName;
$segments[] = $newName;
unset($query['product_id']);
}
return $segments;
}
and parse route function
function componentParseRoute($segments)
{
$app = JFactory::getApplication();
$menu = $app->getMenu();
$item =& $menu->getActive();
$count = count($segments);
switch ($item->query['view']) {
case 'catalogue' : {
$view = 'training';
$id = $segments[1];
}
break;
}
$data = [
'view' => $view,
'product_id' => $id
];
return $data;
}
While on the end of buildroute function segments are ok I have exactly what I want that on the beginning of parse route I have something like
website.com/szkolenie/1-krakow <-- I dont know wtf is this krakow( I know it is city i Poland) but still where is it get from ? The getProductName function implementation is
function getProductName($productId)
{
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select('#__component_training.id as id, #__component_product' . name)
->from($db->quoteName('#__component_training'))
->where('#__s4edu_product.product_id = ' . $productId)
->leftJoin('#__component_product ON
#__component_training.product_id=#__component_product.product_id');
$training = $db->loadObject();
return trim($training->name);
}
So taking all this into consideration I think that something is happening between the buildRoute and parseRoute, something what filters the $segment[1] variable, but how to disable that and why is it happening ?
P.S
Please do not send me to https://docs.joomla.org/Joomla_Routes_%26_SEF
I already know all the tutorials on joomla website which contains anything with sef.
P.S.S
It is built on joomla 3.7.0
You do not have a product named "krakow" ?
If not you can try to remove the $productName from the build function, just to check if this "krakow" is added automaticaly or it's from the getProductName() function.
Also i noticed that you have an error i guess in the function getProductName()
->where('#__s4edu_product.product_id = ' . $productId)
It's should be
->where('#__component_product.product_id = ' . $productId)
I have developed simple application, i have generated checkbox in grid dynamically from database, but my problem is when user select the checkbox and other required field from grid and press submit button, it adds duplicate value, so i want to know how can i check the checkbox value & other field value with database value while submitting data to database.
following code i use to generate all selected items and then save too db
foreach ($this->addattendee->results as $key=>$value)
{
//print_r($value);
$id = $this->Attendee_model->save($value);
}
i am using codeigniter....can any one give the idea with sample code plz
{
$person = $this->Person_model->get_by_id($id)->row();
$this->form_data->id = $person->tab_classid;
$this->form_data->classtitle = $person->tab_classtitle;
$this->form_data->classdate = $person->tab_classtime;
$this->form_data->createddate = $person->tab_crtdate;
$this->form_data->peremail = $person->tab_pemail;
$this->form_data->duration = $person->tab_classduration;
//Show User Grid - Attendee>>>>>>>>>>>>>>>>>>>>>>>>
$uri_segment = 0;
$offset = $this->uri->segment($uri_segment);
$users = $this->User_model->get_paged_list($this->limit, $offset)->result();
// generate pagination
$this->load->library('pagination');
$config['base_url'] = site_url('person/index/');
$config['total_rows'] = $this->User_model->count_all();
$config['per_page'] = $this->limit;
$config['uri_segment'] = $uri_segment;
$this->pagination->initialize($config);
$data['pagination'] = $this->pagination->create_links();
// generate table data
$this->load->library('table');
$this->table->set_empty(" ");
$this->table->set_heading('Check', 'User Id','User Name', 'Email', 'Language');
$i = 0 + $offset;
foreach ($users as $user)
{
$checkarray=array('name'=>'chkclsid[]','id'=>'chkclsid','value'=>$user->user_id);
$this->table->add_row(form_checkbox($checkarray), $user->user_id, $user->user_name, $user->user_email,$user->user_language
/*,anchor('person/view/'.$user->user_id,'view',array('class'=>'view')).' '.
anchor('person/update/'.$user->user_id,'update',array('class'=>'update')).' '.
anchor('person/showattendee/'.$user->user_id,'Attendee',array('class'=>'attendee')).' '.
anchor('person/delete/'.$user->user_id,'delete',array('class'=>'delete','onclick'=>"return confirm('Are you sure want to delete this person?')"))*/ );
}
$data['table'] = $this->table->generate();
//end grid code
// load view
// set common properties
$data['title'] = 'Assign Attendees';
$msg = '';
$data['message'] = $msg;
$data['action'] = site_url('person/CreateAttendees');
//$data['value'] = "sssssssssssssssssss";
$session_data = $this->session->userdata('logged_in');
$data['username'] = "<p>Welcome:"." ".$session_data['username']. " | " . anchor('home/logout', 'Logout')." | ". "Userid :"." ".$session_data['id']; "</p>";
$data['link_back'] = anchor('person/index/','Back to list of Classes',array('class'=>'back'));
$this->load->view('common/header',$data);
$this->load->view('adminmenu');
$this->load->view('addattendee_v', $data);
}
The code is quite messy but I have solved a similar issue in my application I think, I am not sure if its the best way, but it works.
function save_vote($vote,$show_id, $stats){
// Check if new vote
$this->db->from('show_ratings')
->where('user_id', $user_id)
->where('show_id', $show_id);
$rs = $this->db->get();
$user_vote = $rs->row_array();
// Here we are check if that entry exists
if ($rs->num_rows() == '0' ){
// Its a new vote so insert data
$this->db->insert('show_ratings', $rate);
}else{
// Its a not new vote, so we update the DB. I also added a UNIQUE KEY to my database for the user_id and show_id fields in the show_ratings table. So There is that extra protection.
$this->db->query('INSERT INTO `show_ratings` (`user_id`,`show_id`,`score`) VALUES (?,?,?) ON DUPLICATE KEY UPDATE `score`=?;', array($user_id, $show_id, $vote, $vote));
return $update;
}
}
I hope this code snippet gives you some idea of what to do.
maybe i have same trouble with you.
and this is what i did.
<?php
public function set_news(){
$this->load->helper('url');
$slug = url_title($this->input->post('title'), 'dash', TRUE);
$query = $this->db->query("select slug from news where slug like '%$slug%'");
if($query->num_rows()>=1){
$jum = $query->num_rows() + 1;
$slug = $slug.'-'.$jum;
}
$data = array(
'title' => $this->input->post('title'),
'slug' => $slug,
'text' => $this->input->post('text')
);
return $this->db->insert('news', $data);
}
?>
then it works.