cakephp foreach sort with titles - php

Hello
i'm started to learning cakephp framework.And just for start i wanted to write some simple game.
I have user controller wited already (not finished but works :D) and now i started to write equipment. But i stuck at the moment i'm trying to sort foreach by type (helmet, armor, shield etc) and now script output table like this:
Id Owner Name Status Type Cost
1 23 Krasnoludzka Salada B H 100
2 23 Jakieś spodnie B L 10
3 23 Zbroja B A 123
But i wanna to make it like this:
Id Owner Name Status Type Cost
Helmets:
1 23 Krasnoludzka Salada B H 100
4 23 Smocza Salada B H 100
Legs:
2 23 Jakieś spodnie B L 10
Armors:
3 23 Zbroja B A 123
Mine equipments_controller.php:
<?php
class EquipmentsController extends AppController {
var $name = 'Equipments';
var $helpers = array('Html', 'Form');
function index() {
$this->set('equipments', $this->Equipment->find('all', array('conditions' => array('owner='.$this->Session->read('Auth.User.id'), 'status=\'B\''))));
//$this->set('equipments', $this->Equipment->find('owner='.$this->Session->read('Auth.User.id')));
}
function view ($id = null) {
$this->Equipment->id = $id;
$owner = $this->Equipment->read('owner');
if ($owner['Equipment']['owner']==$this->Session->read('Auth.User.id')) {
$this->redirect(array('controller' => 'equipments', 'action' => 'index'));
$this->Session->setFlash('To nie twój przedmiot!');
} else {
$this->set('equipment', $this->Equipment->read());
}
}
}
And equipments/index.ctp:
<!-- File: /app/views/news/index.ctp (edit links added) -->
<h1>Plecak</h1>
<table>
<tr>
<th>Id</th>
<th>Owner</th>
<th>Name</th>
<th>Status</th>
<th>Type</th>
<th>Cost</th>
</tr>
<!-- Here's where we loop through our $news array, printing out news info -->
<?php foreach ($equipments as $equipment): ?>
<tr>
<td><?php echo $equipment['Equipment']['id']; ?></td>
<td><?php echo $equipment['Equipment']['owner']; ?></td>
<td><?php echo $equipment['Equipment']['name']; ?></td>
<td><?php echo $equipment['Equipment']['status'];?></td>
<td><?php echo $equipment['Equipment']['type']; ?></td>
<td><?php echo $equipment['Equipment']['cost']; ?></td>
</tr>
<?php endforeach; ?>
</table>
Can anyone help me?

You can add a 'group' option to your find()...
$this->set(
'equipments',
$this->Equipment->find(
'all',
array(
'conditions' => array(
'Equipment.owner' => $this->Session->read('Auth.User.id'),
'Equipment.status' => 'B'
),
'group' => array(
'Equipment.type'
),
'order' => array(
'Equipment.type',
'Equipment.name',
),
)
)
);
Hopefully you've actually got a Model for those types, and can use that model instead of those Equipment.type values, something like EquipmentType.name would be useful in your view. If you had that, then you'd be able to output a new heading row each time the EquipmentType.id changed.

I I'm understanding you correctly, you'd like to be able to sort your table of data by the titles in the table head tags.
If this is the case, I'd suggest using cake's built in paginator.
Your controller should look like:
class EquipmentsController extends AppController {
var $name = 'Equipments';
var $helpers = array('Html', 'Form');
public $paginate = array(
'Equipment' => array(
'limit' => 25,
'order' => array(
'Equipment.id' => 'ASC'
)
)
);
function index() {
$owner = $this->Session->read('Auth.User.id');
$equipments = $this->paginate('Equipment', array(
'Equipment.owner' => $owner,
'Equipment.status' => 'B'
));
$this->set(compact('equipments'));
}
}
Then in your views/equipments/index.ctp:
<!-- File: /app/views/news/index.ctp (edit links added) -->
<h1>Plecak</h1>
<table>
<tr>
<th><?=$this->Paginator->sort('Id', 'Equipment.id')?></th>
<th><?=$this->Paginator->sort('Owner', 'Equipment.owner')?></th>
<th><?=$this->Paginator->sort('Name', 'Equipment.name')?></th>
<th><?=$this->Paginator->sort('Status', 'Equipment.status')?></th>
<th><?=$this->Paginator->sort('Type', 'Equipment.type')?></th>
<th><?=$this->Paginator->sort('Cost', 'Equipment.cost')?></th>
</tr>
<!-- Here's where we loop through our $news array, printing out news info -->
<?php foreach ($equipments as $equipment): ?>
<tr>
<td><?php echo $equipment['Equipment']['id']; ?></td>
<td><?php echo $equipment['Equipment']['owner']; ?></td>
<td><?php echo $equipment['Equipment']['name']; ?></td>
<td><?php echo $equipment['Equipment']['status'];?></td>
<td><?php echo $equipment['Equipment']['type']; ?></td>
<td><?php echo $equipment['Equipment']['cost']; ?></td>
</tr>
<?php endforeach; ?>
Using the paginator this way will generate links in your table headers that will automatically sort the data coming out of the db.

Related

Click on link in tab but link on second tab is activated

I created a web page with two tabs, each page having a list of links. When I click on a link on first tab, the link on the second tab is activated. That is unless its a row number that exceeds the number of rows on the second tab. The output HTML is correct. Both tabs by themselves work fine.
I am using Yii 1.1.14, php 5.4.11
Controller Action:
public function actionTest5() {
$fileNew = new File;
$criteria = new CDbCriteria;
$criteria->select='id,name,description';
$criteria->condition='t.user_id='.(int)Yii::app()->user->id;;
$criteria->order='t.date_updated desc, t.date_entered desc';
$criteria->limit=5;
$templateList=File::model()->findAll($criteria);
$criteria = new CDbCriteria;
$criteria->select='id,name,description';
$criteria->condition='t.user_id='.(int)Yii::app()->user->id;;
$criteria->order='t.date_updated desc, t.date_entered desc';
$criteria->limit=3;
$listFile= Listfile::model()->findAll($criteria);
$docI = new Document;
$fileNew = new File;
$url = Yii::app()->createUrl('test/setup');
if(isset($_POST['File']) OR isset($_POST['Document']))
$this->redirect($url);
$this->render('test5', array(
'model'=>$docI,
'templateList'=>$templateList,
'listFile'=>$listFile,
'fileNew'=>$fileNew,
));
}
View File test5:
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'setup-form',
'enableClientValidation'=>true,
));
$tabArray=array();
$tabArray["Tab1"] = array(
'id'=>'1',
'content'=>$this->renderPartial('_testTab1',
array(
'tabNum'=>1,
'form'=>$form,
'model'=>$model,
'templateList'=>$templateList,
),TRUE));
$tabArray["Tab2"] = array(
'id'=>'2',
'content'=>$this->renderPartial('_testTab2',
array(
'tabNum'=>2,
'form'=>$form,
'model'=>$model,
'listFile'=>$listFile,
),TRUE));
$this->widget('zii.widgets.jui.CJuiTabs',array(
'tabs'=>$tabArray,
'id'=>'MyTab-Menu',
));
?>
<?php $this->endWidget(); ?>
</div>
This is the partial view _testTab1:
<table class="setup">
<?php echo '<thead><th></th><th>File Name</th><th>Load File</th><th>Delete</th></thead>' ?>
<?php foreach ($templateList as $i=>$file): ?>
<tr id="trow">
<td><?php echo CHtml::activeHiddenField($file, "[$i]id"); ?></td>
<td><?php echo 'fileID: ['.$file['id'].']'; ?></td>
<td><?php
echo CHtml::link('Reload File','#',
array('submit'=>array('setupFile','id'=>$i),
'id' => 'setup_' . $i . '_reload',
'value' => (int) $i,
'name' => 'setupFile',
));
?></td>
<td><?php
echo CHtml::link('Delete','#',
array('submit'=>array('fileDelete','id'=>$i),
'id' => 'setup_' . $i . '_delete',
'value' => (int) $i,
'name' => 'delete',
'confirm' => 'Are you sure you want to delete file '.$file['id'].'?',
));
?></td>
</tr>
<?php endforeach; ?>
</table>
This is the partial view _testTab2:
<table class="setup">
<?php echo '<thead><th></th><th>File Name</th><th>Load File</th><th>Delete</th></thead>' ?>
<?php foreach ($listFile as $i => $file): ?>
<tr id="trow">
<td><?php echo CHtml::activeHiddenField($file, "[$i]id"); ?></td>
<td><?php echo 'fileID: ['.$file['id'].']'; ?></td>
<td><?php
echo CHtml::link('Reload File','#',
array('submit'=>array('setupFileList','id'=>$i),
'id' => 'setup_' . $i . '_reload',
'value' => (int) $i,
'name' => 'setupFileList',
));
?></td>
<td><?php
echo CHtml::link('Delete','#',
array('submit'=>array('fileListDelete','id'=>$i),
'id' => 'setup_' . $i . '_delete',
'value' => (int) $i,
'name' => 'delete',
'confirm' => 'Are you sure you want to delete file '.$file['id'].'?',
));
?></td>
</tr>
<?php endforeach; ?>
</table>
On post, the File[x]['id']'s are set with the x=row number and id being the hidden field (same applies to Listfile for second tab rows). When Reload is clicked, the following action is loaded. It gets the x value (row number) and from that determines the id value. Then it loads the test/uploadFile/id page. The problem is that when I click on the Reload (or delete) link for the first three rows on the first tab, I get the id for the second tab. When I do this for the last two rows on the first tab, I get the correct id value. All links on the second tab work as expected as do each of the tabs if they are loaded individually.
public function actionSetupFile($id) {
$fileName='';
if(isset($_POST['File'])) {
if(isset($_POST['File'][(int)$id]['id'])) {
$selected = $_POST['File'][(int)$id]['id'];
$file=new File;
$fileName=$file->getFileName($selected);
$url = Yii::app()->createUrl('test/UploadFile/'.CHtml::encode((int)$selected));
}
} else {
$msg = 'Unable to complete request to upload file; try again ';
$url = Yii::app()->createUrl('test/setup');
}
$this->redirect($url, array(
'fileName'=>$fileName,
));
}
public function actionSetupFileList($id=null) {
$fileName='';
if(isset($_POST['Listfile'])) {
if(isset($_POST['Listfile'][(int)$id]['id'])) {
$selected = $_POST['Listfile'][(int)$id]['id'];
$file=new Listfile;
$fileName=$file->getFileListName($selected);
$url = Yii::app()->createUrl('test/UploadFileList/'.CHtml::encode((int)$selected));
}
} else {
$msg = 'Unable to complete request to upload file; try again ';
$url = Yii::app()->createUrl('test/setup');
}
$this->redirect($url, array(
'fileName'=>$fileName,
));
}
The post indices must be different for each tab. One way to do this is to use a multiplier for the second tab, defined as $k=100*($i+1); $i+1 because $i is 0 first and index for first row would be 0 for both tabs. Of course, some other multiplier could be used.
<table class="setup">
<?php echo '<thead><th></th><th>File Name</th><th>Load File</th><th>Delete</th></thead>' ?>
<?php foreach ($listFile as $i => $file): $k=($i+1)*100; ?>
<tr id="trow">
<td><?php echo CHtml::activeHiddenField($file, "[$k]id"); ?></td>
<td><?php echo 'fileID: ['.$file['id'].']'; ?></td>
<td><?php
echo CHtml::link('Reload File','#',
array('submit'=>array('setupFileList','id'=>$k),
'id' => 'setup_' . $k . '_reload',
'value' => (int) $k,
'name' => 'setupFileList',
));
?></td>
<td><?php
echo CHtml::link('Delete','#',
array('submit'=>array('fileListDelete','id'=>$k),
'id' => 'setup_' . $k . '_delete',
'value' => (int) $k,
'name' => 'delete',
'confirm' => 'Are you sure you want to delete file '.$file['id'].'?',
));
?></td>
</tr>
<?php endforeach; ?>
</table>
Alternatively, pass offset from view file (test5) where offset for second and subsequent tabs is count of entries in ALL prior tabs (i.e. 2nd tab: $offset=count($templateList)). Then instead of $k above, use $i + $offset):

CakePHP: Cannot determine the total working hours of employees

What I want:- I want to calculate the total working hours of my employees based on the working hours of multiple days.
My problem the total working hours ($total_hours) is not working.
My Model
class Attendence extends AppModel {
function add($data){
if (!empty($data)) {
$this->create();
if($this->save($data)) {
return true ;
}
}
}
function fetchdata() {
return $this->find('all', array('conditions' => array('Attendence.date' > '2014-04-01',
'AND' => array('Attendences.date' < '2014-04-21'),
)));
}
}
My Controller
class EmployeesController extends AppController {
public $uses = array('Employee', 'Attendence', 'InsertDate');
public function add()
{
if($this->Employee->add($this->request->data)==true){
$this->redirect(array('action'=>'index'));
}
}
public function index(){
$this->set('employees',$this->Employee->Fetch());
$this->set('attendence',$this->Attendence->fetchdata());
$this->set('dates',$this->InsertDate->fetchdate());
}
}
My View
<div class="index">
<table>
<thead>
<th>Num</th>
<th>Employee</th>
<th>Salary/Hour</th>
<th>Start Date</th>
<th>End Date</th>
<th>Total Hour</th>
<th>Total Salary</th>
</thead>
<?php
$id = 0;
foreach($employees as $e):?>
<? $id++ ?>
<tr>
<td><?php echo $e{'Employee'}{'id'} ?></td>
<td><?php echo $e['Employee']['firstname'], $e['Employee']['lastname'] ?></td>
<td style="text-align:center"><?php echo $e['Employee']['salary'] ?></td>'
<?php foreach($dates as $d):?>
<td><?php echo $d['InsertDate']['start_date'] ?></td>
<td><?php echo $d['InsertDate']['end_date'] ?></td>
<?php
$total_hours = 0;
foreach ($attendence as $et){
$ts1 = strtotime($et['Attendence']['in_time']);
$ts2 = strtotime($et['Attendence']['out_time']);
$diff = abs($ts1 - $ts2) / 3600;
$total_hours += number_format($diff,2);
}
//Total hours
echo '<td style="text-align:center">'.$total_hours.'</td>';
//Total Salary
echo '<td style="text-align:center">'.$total_hours*$e['Employee']['salary'].'</td>';
?>
<?php endforeach; ?>
<?php endforeach; ?>
</tr>
</table>
</div>
A programmer friend of mine gave me a solution. But I dont know how to implement in CAKEPHP
I am updating the solution also
Look at here :
$total_hours = 0;
foreach ($attendence as $et){
$ts1 = strtotime($et['Attendence']['in_time']);
$ts2 = strtotime($et['Attendence']['out_time']);
$diff = abs($ts1 - $ts2) / 3600;
$total_hours += number_format($diff,2);
}
The code shows you that there is an array. the array contains (attendance id and in_time and out_time in each point).
The Important thing is you should check how you fill this array.
In the above foreach that you generate the table by $employees array , you have the (employee_id) wich name (id) here
So you should write a new query in your view!!!In the middle of your first foreach and before second foreach
before this line :
$total_hours = 0
You have to write a query and fetch data from DB like this :
//SELECT * FROM attendences
WHERE attendences.date > '2014-04-23' AND attendences.date < '2014-04-30'
AND id=$e['Employee']['id'] // is your employee_id in your first array.
So when you fetched data , You have a new array named "$attendence"
Then , your second foreach(which calculates the salary and total hours) should work correctly

How implement multiple editable column with yii-booster?

Am working on a Yii staff-hours scheduling project, stuck on editable-curd-staffhours-module. I want to store staff scheduling hours in StaffHourstable using Editable Yii Booster Extension.
My staffhours table DB stucture as:
id(pk) user_id(fk) staff_id(int) monday(text) tuesday(text) wednesday(text) thursday(text) friday(text) saturday(text) sunday(text)
All day-text fields used to store serialize time as in associative-array format:
array(
'12:00 AM' => 'open',
'12:30 AM' => 'close',
'01:00 AM' => 'close',
'01:30 AM' => 'open',
'02:00 AM' => 'open',
.
.
.
'11:00 PM' => 'close'
'11:30 PM' => 'close'
);
I have implemented Editable UI using Yii Booster Extension, watch snap below:
Problem is that am unable to recognize how to store/update staff-hours data in DB.
Some Of Code i have done
---- In View ----
<?php
$this->breadcrumbs=array(
'Settings'=>array('settings/settings'),
'Staff Hours',
);
$user_id = Yii::app()->user->getId();
$condition = "user_id = '$user_id'";
$data = StaffHours::model()->findAll();
$Monday = unserialize($data[0]['monday']);
$Tuesday = unserialize($data[0]['tuesday']);
$Wednesday = unserialize($data[0]['wednesday']);
$Thursday = unserialize($data[0]['thursday']);
$Friday = unserialize($data[0]['friday']);
$Saturday = unserialize($data[0]['saturday']);
$Sunday = unserialize($data[0]['sunday']);
foreach($data as $data)
{
?>
<div id="settinghead">StaffS Hours </div>
<div id="leftmenu"> <?php $this->widget('application.components.widgets.SettingsMenu.settingsmenuWidget'); ?></div>
<div id="rightcontent">
<div id="pageheding">Staff Hours Detail </div>
<table class="items table table-bordered">
<thead>
<tr><th scope="col">Time</th> <th scope="col">Monday</th> <th scope="col">Tuesday</th><th scope="col">Wednesday</th>
<th scope="col">Thursday</th><th scope="col">Friday</th><th scope="col">Saturday</th><th scope="col">Sunday</th> </tr>
</thead>
<?php
$start = strtotime('12:00am');
$end = strtotime('11:59pm');
for( $i = $start; $i <= $end; $i += 900)
{
$time = date('h:i A', $i);
?>
<tr>
<th scope="row"><?php echo $time; ?></th>
<td id="mon<?php echo $time; ?>">
<?php
$this->widget('bootstrap.widgets.TbEditableField', array(
'type' => 'select',
'model' => $data,
'emptytext' => $Monday[$time],
'attribute' => 'monday',
'url' => $this->createUrl('staffhours/updatetime&time='.$time), //url for submit data
'source' => array('Open', 'Close', 'Away'),
'value' => $time,
'enabled' => true
));
?>
</td>
<td id="tue<?php echo date('g:i A', $i); ?>"><?php echo $Tuesday[$time]; ?></td>
<td id="wed<?php echo date('g:i A', $i); ?>"><?php echo $Wednesday[$time]; ?></td>
<td id="thu<?php echo date('g:i A', $i); ?>"><?php echo $Thursday[$time]; ?></td>
<td id="fri<?php echo date('g:i A', $i); ?>"><?php echo $Friday[$time]; ?></td>
<td id="sat<?php echo date('g:i A', $i); ?>"><?php echo $Saturday[$time]; ?></td>
<td id="sun<?php echo date('g:i A', $i); ?>"><?php echo $Sunday[$time]; ?></td>
</tr>
<?php
}
}
?>
</table>
</div>
---- In StaffHoursController Controller ----
/**
* Update time.
*/
public function actionUpdatetime($time)
{
$user_id = Yii::app()->user->getId();
$pk = $_POST['pk'];
$day = $_POST['name'];
$status = $_POST['value'];
$GetData = StaffHours::model()->findByPk($pk);
$DayTimes = unserialize($GetData->monday);
if(array_key_exists($time, $DayTimes))
{
unset($DayTimes[$time]);
//merge new value
$DayTimes[$time] = $status;
array_push($DayTimes, $DayTimes[$time]);
$attributes = array($day => serialize($DayTimes));
$condition = "id = '$pk' AND user_id = '$user_id'";
StaffHours::model()->updateByPk($pk, $attributes, $condition);
}
}
If am going wrong or another easy way available to staff hours using Editable-UI.
Then please suggest a better way to store Staff-Hours using Editable-UI.
I believe storing array data into MySql text column is very impractical, since you will loose performance, ability to implement proper searching technique and etc. A better database design can be:
Each staff has many hours, and each hour can be assigned to many staff, a simple MANY_MANY relationship.
The advantage is that you can search for any date, any hour, any staff with a very easy,simple, singe query, or ActiveRecord:

how can i write an algorithm to multiply the total * quantity in a shopping cart using php $_SESSION?

I am writing a shopping cart and have my data stored in the $_SESSION array, but would like to calculate a total. below it the code I thought would work to do this, but it returns '1' in stead of a total!
$total = array($_SESSION['qty'],$_SESSION['pr']);
/* I'll give you more code...thanks for your help!!
here is the code for my php cart:
<?php
function item_list()
{
if(isset($_SESSION['qty'])){
$total = array($_SESSION['qty'],$_SESSION['pr']);
foreach($_SESSION['qty'] as $key => $value)
{?>
<tr>
<td align="center"><?php echo $_SESSION['item'][$key]; ?></td>
<td align="center"><?php echo $value; ?></td>
<td align="center"><?php echo $_SESSION['pr'][$key]; ?></td>
<td align="center"><?php echo array_product($total); ?>
</tr><?php
}
}
}
session_start();
if(isset($_POST['clear']) && ($_POST['clear'] == 'clear'))
{
session_destroy();
unset($_SESSION['qty']);
unset($_SESSION['item']);
unset($_SESSION['pr']);
unset($_POST['qty']);
unset($_POST['item']);
unset($_POST['pr']);
}
if(!isset($_SESSION['qty'])) $_SESSION['qty'] = array();
if(!isset($_SESSION['item'])) $_SESSION['item'] = array();
if(!isset($_SESSION['pr'])) $_SESSION['pr'] = array();
if(isset($_POST['qty']))
{
foreach($_POST['qty'] as $value)
{
if(!$value == '') array_push($_SESSION['qty'], filter_var($value,
FILTER_SANITIZE_SPECIAL_CHARS));
}
foreach($_POST['item'] as $key => $value)
{
if(!$_POST['qty'][$key] == '') array_push($_SESSION['item'], filter_var($value,
FILTER_SANITIZE_SPECIAL_CHARS));
}
foreach($_POST['pr'] as $key => $value)
{
if(!$_POST['qty'][$key] == '') array_push($_SESSION['pr'], filter_var($value,
FILTER_SANITIZE_SPECIAL_CHARS));
}
}
?>
That is a strange way to structure a shopping cart, but here's how to do it with that structure:
foreach($_SESSION['qty'] as $key => $value)
{
$total = $_SESSION['qty'][$key] * $_SESSION['pr'][$key];
?>
<tr>
<td align="center"><?php echo $_SESSION['item'][$key]; ?></td>
<td align="center"><?php echo $value; ?></td>
<td align="center"><?php echo $_SESSION['pr'][$key]; ?></td>
<td align="center"><?php echo $total; ?>
</tr><?php
}
If you wanted to get a total of all quantity and cost of the cart:
function getTotals()
{
$total = array('qty' => 0, 'price' => 0);
foreach($_SESSION['qty'] as $key => $qty)
{
$total['qty'] += $qty;
$total['price'] += ($_SESSION['pr'][$key] * $qty)
}
return $total;
}
$total = getTotals();
echo $total['qty']; // output the total quantity of items
echo $total['price']; // output the total cost for all items and quantity
I would recommend a better structure though, something like:
$_SESSION['cart']['items'] = array(
array(
'name' => 'Screwdriver',
'price' => 5,
'qty' => 2,
),
array(
'name' => 'Hammer',
'price' => 10,
'qty' => 1,
)
);
As per your cart array it is not able to hold multiple products you have to use multy dimensional array like this
$_SESSION['cart_items'] = array(
array( "qty"=>5, "item"=>"tshirt", "pr"=>50.20),
array( "qty"=>2, "item"=>"Cell Phone", "pr"=>50.20),
array( "qty"=>7, "item"=>"", "pr"=>50.20),
)
then you can write your code like this
function item_list()
{
foreach($_SESSION['cart_items'] as $item_array)
{?>
<tr>
<td align="center">Item:<?php echo $item_array['item']; ?></td>
<td align="center">Qty: <?php echo $item_array['qty']; ?></td>
<td align="center">Price :<?php echo $item_array['pr']; ?></td>
<td align="center">Total : <?php echo $item_array['qty'] * $item_array['pr']; ?>
</tr><?php
}
}
You should create yourself a Card class that is able to import/export data from the $_SESSION superglobal (or some other array if you mock it for tests, testing with $_SESSION can be akward) which is able to handle your data-structure easily and can calculate the total, too:
$cart = new Cart();
$cart->importFromArray($_SESSION);
// or:
$cart->importFromArray($_SESSION['cart']);
// later on:
$total = $cart->getTotal();
// somewhere else:
$cart->addItem(...);
...
$_SESSION['cart'] = $cart->exportToArray();
That will allow you to more easily change the code over time.

PHP: fill array from resultset

The code shown below is used to manually fill an array.
<?php
include_once 'include/DatabaseConnector.php';
$data = array(
array(0,array("111",' EE112',' AA','FT445'),"2004-03-01 10:00","2004-03-01 14:00"),
array(1,array("111",' BC124',' RYA','FE675'),"2004-03-01 16:00","2004-03-01 18:00"),
array(2,array("11",' BE225',' FA','AE667'),"2004-03-01 09:00","2004-03-01 10:00"),
array(3,array("11",' TC828',' BA','FF745'),"2004-03-01 06:00","2004-03-01 08:00")
);
?>
Now I want to fill this array from the database:
$query1="SELECT * FROM MyData;";
$result1=DatabaseConnector::ExecuteQueryArray($query1);
<?php foreach ($result1 as $row):?>
<tr>
<td><?php echo $row['resReg']; ?></td>
<td><?php echo $row['resTitle']; ?></td>
<td><?php echo $row['resAvailability'] ? 'Yes' : 'No';?></td>
</tr>
<?php endforeach;?>
How to assign the columns of result1 to the columns of the array?
Am i right assuming you want to do something like this:
<?php
$query1 = "SELECT name,color1,color2 FROM MyPets;";
$result1 = DatabaseConnector::ExecuteQueryArray($query1);
$petArray = array();
foreach($result1 as $pet):
$petArray[] = array('name' => $pet['name'],
'colors' => array(
$pet['color1'],
$pet['color2'])
);
?>

Categories