robertrutenge
robertrutenge

Reputation: 678

PHP For each Loop returns one value

I am having a small confusion here, i am creating a calender using a laravel plugin by Crinsane, the only problem is displaying multiple dates from my values delivered from the database using foreach loop. The basic structure is this

$data = array(
    3  => 'http://example.com/news/article/2006/03/',
    7  => 'http://example.com/news/article/2006/07/',
);

Calendar::generate(2006, 6, $data);

This will render a calender. But my data values are from database. This is my foreach loop

   @foreach ($events as $a)
       <?php  $string = $a->datebooked;
       $date = DateTime::createFromFormat("Y-m-d" ,$string);
       $date=$date->format("d");
       $date;?>
       <?php $data=array(
           $date=> $a->eventname,
         )?>
   @endforeach

 <?php echo Calendar::generate(date('Y'), date('n'), $data); ?>

When i run this code, it only displays the last event date, i know it is because it loops through the whole data variable, but how can i make it loop through $date=> $a->eventname only ?

Upvotes: 0

Views: 1095

Answers (1)

Chris Forrence
Chris Forrence

Reputation: 10094

Outside of the for-each loop, you don't want to overwrite $data, but add to it. The quick and dirty way to do this is to define a $data array outside the foreach-loop, then append to the array like such

<?php
$data = array();
?>
@foreach ($events as $a)
   <?php

   $string = $a->datebooked;
   $date = DateTime::createFromFormat("Y-m-d", $string);
   $date = $date->format("d");
   $data[] = array($date => $a->eventname);
   ?>
@endforeach

This isn't a great way to mix PHP into your view, though; as a suggestion, I'd put the logic to create $data into your controller, and only call Calendar::generate in the view.

Upvotes: 1

Related Questions