I am currently working with the lat.fm api to develop an app.
I have a function which runs to pull in the weekly track listing from a last.fm group.
The aim is to pull in the album artwork and to make a "gridview" template.
The below code does this:
public function getWeeklyTrackChartGrid($methodVars) {
// Check for required variables
if ( !empty($methodVars['group']) ) {
$vars = array(
'method' => 'group.getweeklytrackchart',
'api_key' => $this->auth->apiKey
);
$vars = array_merge($vars, $methodVars);
if ( $call = $this->apiGetCall($vars) ) {
$i = 0;
//shuffle($call->weeklytrackchart->track);
$loopN = $call->weeklytrackchart->track;
foreach ($loopN as $track ) {
require 'config.php';
//if(++$i > $userLimit*2) break;
$albumArtS = $tracks['album']['image']['small'] = (string) $track->image[0];
$albumArtM = $tracks['album']['image']['small'] = (string) $track->image[1];
$albumArtL = $tracks['album']['image']['small'] = (string) $track->image[2];
$playCounts = $tracks[$i]['playcount'] = (string) $track->playcount;
?>
<?php if ($playCounts > 1) { ?>
<?php if ($albumArtL) { ?>
<img src="<?php echo $albumArtL; ?>" />
<?php } ?>
<?php } else { ?>
<?php if ($albumArtM) { ?>
<img src="<?php echo $albumArtM; ?>" />
<?php } ?>
<?php } ?>
<?php if ($albumArtwork == "yes") { ?>
<?php if ($albumArt) { ?>
<?php } }?>
<?php $i++;
}
return $tracks;
}
else {
return FALSE;
}
}
else {
// Give a 91 error if incorrect variables are used
$this->handleError(91, 'You must include a group variable in the call for this method');
return FALSE;
}
}
I would like to use the php function shuffle on the foreach loop to randomise the tracks, rather than pull them in, in the order last.fm gives them you.
As you can see i havent commented the shuffle function out above, as when i add this i get the following warning:
Warning: shuffle() expects parameter 1 to be array, object given in
Any ideas on what could be the problem?
Cheers,
Dan
$loopN = (array) $call->weeklytrackchart->track;
shuffle($loopN);
Related
I am getting this error
PHP Warning: Invalid argument supplied for foreach()
for this line
{$ret = json_encode_jsfunc($value, $funcs, 1);$input[$key]=$ret[0];$funcs=$ret[1];}
Which is part of this
/**
* Function to encode JS function reference from PHP array
* http://www.php.net/manual/en/function.json-encode.php#105749
*/
function json_encode_jsfunc($input=array(), $funcs=array(), $level=0)
{
foreach($input as $key=>$value)
{
if (is_array($value))
{
$ret = json_encode_jsfunc($value, $funcs, 1);
$input[$key]=$ret[0];
$funcs=$ret[1];
}
else
{
if (substr($value,0,8)=='function')
{
$func_key="#".rand()."#";
$funcs[$func_key]=$value;
$input[$key]=$func_key;
}
// for json data, incase of local array
else if (substr($value,0,2)=='[{')
{
$func_key="#".rand()."#";
$funcs[$func_key]=$value;
$input[$key]=$func_key;
}
}
}
if ($level==1)
{
return array($input, $funcs);
}
else
{
$input_json = json_encode($input);
foreach($funcs as $key=>$value)
{
$input_json = str_replace('"'.$key.'"', $value, $input_json);
}
return $input_json;
}
}
/*
This error is transient.
It occurs in only some instances.
I've looked at the database records that are being passed into this function and there is no difference between the records that cause this issue and those that don't. However, it is always the same records that cause the error.
The code is being called from:
// multiple search group function
if ($this->actions["search"] == "group")
{
$this->options["search_options"]["multipleSearch"] = true;
$this->options["search_options"]["multipleGroup"] = true;
}
$this->options["search_options"]["sopt"] = array('eq','ne','lt','le','gt','ge','bw','bn','in','ni','ew','en','cn','nc','nu','nn');
$out = json_encode_jsfunc($this->options);
$out = substr($out,0,strlen($out)-1);
and
<?php ### P ### ?>
if (typeof(opts) != 'undefined') extra_opts = opts;
if (typeof(opts_<?php echo $grid_id?>) != 'undefined') extra_opts = opts_<?php echo $grid_id?>;
// if bootstrap, increase subgrid icon width
if (jQuery("link[href*='ui.bootstrap']").length)
extra_opts["subGridWidth"] = "33px";
var grid_<?php echo $grid_id?> = jQuery("#<?php echo $grid_id?>").jqGrid( jQuery.extend(<?php echo $out?>, extra_opts ) );
jQuery("#<?php echo $grid_id?>").jqGrid('navGrid','#<?php echo $grid_id."_pager"?>',
<?php echo json_encode_jsfunc($this->navgrid["param"])?>,
<?php echo json_encode_jsfunc($this->options["edit_options"])?>,
<?php echo json_encode_jsfunc($this->options["add_options"])?>,
<?php echo json_encode_jsfunc($this->options["delete_options"])?>,
<?php echo json_encode_jsfunc($this->options["search_options"])?>,
<?php echo json_encode_jsfunc($this->options["view_options"])?>
);
and
// Set grouping header using callGridMethod
<?php if (!empty($this->group_header)) { ?>
jQuery("#<?php echo $grid_id?>").jqGrid("setGroupHeaders", <?php echo json_encode_jsfunc($this->group_header)?>);
<?php } ?>
and also
jQuery('#<?php echo $grid_id?>').jqGrid('editGridRow', ids, <?php echo json_encode_jsfunc($this->options["edit_options"])?>);
example of a record that brings up error:
{
"idstaging" : 17,
"category" : "nutrigenetics",
"subcategory" : "methylation",
"gene" : "MTHFR",
"rs" : "rs1801133",
"taqman" : "C___1202883_20",
"var_alias" : "C677T",
"notes" : ""
}
example of a record that does NOT bring up error
{
"idstaging" : 20,
"category" : "nutrigenetics",
"subcategory" : "methylation",
"gene" : "MTRR",
"rs" : "rs1801394",
"taqman" : "C___3068176_10",
"var_alias" : "A66G",
"notes" : ""
}
<?php
print_r($optimum);
$dataNumRows = count($optimum);
?>
<?php for ($i = 0; $i < $dataNumRows; $i++) : ?>
<?php echo $cFirstName; ?>
<?php echo $cLastName; ?>
<?php endfor; ?>
My print_r inserted in my VIEW shows the following:
Array ( [cFirstName] => Array ( [0] => Tom [1] => Alexa ) [cLastName] => Array ( [0] => Jones [1] => Planter ) )
My MODEL is the following
//Get all the customers currently pending
//install for the user making the request.
function getAllCustomersPendingInstall()
{
$data=array();
//Need to use sessions to display proper
//records for each user. Temp set id to user #7
$id = 7;
//query the db and return all record where SalesRepId == $id
$query = $this->db->get_where('customers', array('SalesRepId' => $id));
//check logic, if rows exist RETURN all rows, else
//return message that no pending installs is available.
if($query->num_rows != 0) {
foreach($query->result() as $row) {
$data['cFirstName'][] = $row->customerFirstName;
$data['cLastName'] [] = $row->customerLastName;
}
} else {
$data = "No pending installs available!";
return $data;
}
//the following var_dump is only showing the last record.
//need to show all rows (which should be 2)
//var_dump($data); exit;
return $data;
}
My CONTROLLER is the following
{
$this->load->library('table');
$this->load->model('GetData');
$data['optimum'] = $this->GetData->getAllCustomersPendingInstall();
$this->load->view('welcome_message', $data);
}
And my question is how do I properly use the FOR loop in my VIEW so that I can loop through all the returned rows. As you can see the print_r is properly returning the proper rows- However I am unable to loop through them. Thanks for the help! Much appreciated!
Try this in your view:
<?php for ($i = 0; $i < $dataNumRows; $i++) : ?>
<?php echo $optimum['cFirstName'][$i]; ?>
<?php echo $optimum['cLastName'][$i]; ?>
<?php endfor; ?>
I think what you're trying to do is get an associative array for each row returned from the database. Correct me if I'm wrong about that.
Should fix your problem
$data = array();
$data_index = 0;
if($query->num_rows != 0) {
foreach($query->result() as $row) {
$data[$data_index]['cfirst'] = $row->customerFirstName;
$data[$data_index]['clast'] = $row->customerLastName;
$data_index++;
}
} else {
$data = "No pending installs available!";
return $data;
}
then in your view (where $customer is the $data array)
<?php foreach($customer as $c):?>
<?php echo $c['cfirst'];?>
<?php endforeach;?>
i'm currently trying to modify a module that works almost perfectly for my requirements, but lacks pagination. I can't seem to grasp how i should add the pagination to it; most JPagination examples assume i have access to the query but in this module (which uses JFactory, JmoduleHelper & JModel) i don't see the query in order to add the limits and such.
mod_otmininews.php
//No direct access!
defined('_JEXEC') or die;
// Include the syndicate functions only once
require_once dirname(__FILE__).DS.'helper.php';
$doc = &JFactory::getDocument();
$doc->addStyleSheet(JURI::base().'/modules/mod_otmininews/css/layout.css');
$list = modOtMiniNewsHelper::getList($params);
$moduleclass_sfx = htmlspecialchars($params->get('moduleclass_sfx'));
require JModuleHelper::getLayoutPath('mod_otmininews', $params->get('layout', 'default'));
helper.php
//No direct access!
defined('_JEXEC') or die;
require_once JPATH_SITE.'/components/com_content/helpers/route.php';
jimport('joomla.application.component.model');
JModel::addIncludePath(JPATH_SITE.'/components/com_content/models');
abstract class modOtMiniNewsHelper
{
public static function getList(&$params)
{
// Get the dbo
$db = JFactory::getDbo();
// Get an instance of the generic articles model
$model = JModel::getInstance('Articles', 'ContentModel', array('ignore_request' => true));
// Set application parameters in model
$app = JFactory::getApplication();
$appParams = $app->getParams();
$model->setState('params', $appParams);
// Set the filters based on the module params
$model->setState('list.start', 0);
$model->setState('list.limit', (int) $params->get('count', 3));
$model->setState('filter.published', 1);
// Access filter
$access = !JComponentHelper::getParams('com_content')->get('show_noauth');
$authorised = JAccess::getAuthorisedViewLevels(JFactory::getUser()->get('id'));
$model->setState('filter.access', $access);
// Category filter
$model->setState('filter.category_id', $params->get('catid', array()));
// User filter
$userId = JFactory::getUser()->get('id');
switch ($params->get('user_id'))
{
case 'by_me':
$model->setState('filter.author_id', (int) $userId);
break;
case 'not_me':
$model->setState('filter.author_id', $userId);
$model->setState('filter.author_id.include', false);
break;
case '0':
break;
default:
$model->setState('filter.author_id', (int) $params->get('user_id'));
break;
}
// Filter by language
$model->setState('filter.language',$app->getLanguageFilter());
// Featured switch
switch ($params->get('show_featured'))
{
case '1':
$model->setState('filter.featured', 'only');
break;
case '0':
$model->setState('filter.featured', 'hide');
break;
default:
$model->setState('filter.featured', 'show');
break;
}
// Set ordering
$order_map = array(
'm_dsc' => 'a.modified DESC, a.created',
'mc_dsc' => 'CASE WHEN (a.modified = '.$db->quote($db->getNullDate()).') THEN a.created ELSE a.modified END',
'c_dsc' => 'a.created',
'p_dsc' => 'a.publish_up',
'h_dsc' => 'a.hits',
);
$ordering = JArrayHelper::getValue($order_map, $params->get('ordering'), 'a.publish_up');
$dir = 'DESC';
$model->setState('list.ordering', $ordering);
$model->setState('list.direction', $dir);
$items = $model->getItems();
foreach ($items as &$item) {
$item->slug = $item->id.':'.$item->alias;
$item->catslug = $item->catid.':'.$item->category_alias;
if ($access || in_array($item->access, $authorised))
{
// We know that user has the privilege to view the article
$item->link = JRoute::_(ContentHelperRoute::getArticleRoute($item->slug, $item->catslug));
}
else {
$item->link = JRoute::_('index.php?option=com_user&view=login');
}
//$item->title = htmlspecialchars( $item->title );
$item->content= strip_tags(preg_replace('/<img([^>]+)>/i',"",$item->introtext));
$item->content = substr($item->content, 0, $params->get('introtext_limit'));
preg_match_all('/img.+src="([^"]+)"/i', $item->introtext, $matches);
if(empty($matches[1][0])){
$item->images="";
}else{
$item->images= $matches [1] [0];
}
//Show thumbnails
if($params->get('showthumbnails')==1){
if($item->images == ""){
$item->thumbnail = '<img src="'.$params->get('directory_thumbdefault').'" width="'.$params->get('thumbwidth').'" height="'.$params->get('thumbheight').'" alt="'.$item->title.'" />';
}else{
$item->thumbnail = '<img src="' .$item->images.'" width="'.$params->get('thumbwidth').'" height="'.$params->get('thumbheight').'" alt="'.$item->title.'" />' ; //show images
}
}
$item->created_date = $item->created;
}
return $items;
}
}
All this code creates an array used by
default.php
defined('_JEXEC') or die;
?>
<div class="ot_news">
<div class="ot_news_i">
<?php
$count = 0;
foreach ($list as $item) : ?>
<?php $count++; ?>
<div class="ot_items <?php echo ($params->get('count') == $count)?'last-item':''; ?>">
<!-- Show thumbnails -->
<?php if($params->get('showthumbnails') == 1){?>
<div class="ot_thumbs" style="width:<?php echo $params->get('thumbwidth')?>px; height:<?php echo $params->get('thumbheight')?>px;">
<?php if($params->get('enablelinkthumb') == 1) {?>
<?php echo $item->thumbnail ;?>
<?php } else { ?>
<?php echo $item->thumbnail?>
<?php }?>
</div>
<?php } else { ?>
<?php echo ''; ?>
<?php } ?>
<!-- End -->
<!-- Show Titles -->
<div class="ot_articles">
<?php if($params->get('showtitle') == 1) { ?>
<div class="ot_title">
<?php if($params->get('enablelinktitle') == 1) { ?>
<?php echo $item->title; ?>
<?php }else{?>
<span class="title"><?php echo $item->title; ?></span>
<?php }?>
</div>
<?php } ?>
<!-- Show Created Date -->
<?php
if ($params->get('show_date') == 1) {
echo '<p class="createddate"><span class="ot_date">';
$date = $item->created_date;
echo JHTML::_('date', $date, $params->get( 'date_format' ));
echo '</span></p>';
}
?>
<!-- Show Content -->
<div class="ot_content"><?php echo $item->content; ?></div>
<!-- Show Readmore -->
<?php if($params->get('readmore') == 1) {?>
<div class="ot_readmore"><?php echo JText::_('READMORE') ?></div>
<?php }else {?>
<?php echo ''; ?>
<?php } ?>
</div>
</div>
<div class="spaces"></div>
<?php endforeach; ?>
</div>
</div>
<div class="ot-mini-news"><?php echo JText::_('ABOUT_OT_MINI_NEWS'); ?></div>
that just uses a for each to show the items with their photos links and descriptions.
So as you can see i have seriously no clue where to add the Pagination code, and i suspect they even use some part of it for the display (i saw a getlist function in the helper.php file.
Any help would be much appreciated.
http://docs.joomla.org/Using_JPagination_in_your_component This is a highly useful document for this - even though this is for a module and the wiki page is using it for a component.
$db =& JFactory::getDBO();
$lim = $mainframe->getUserStateFromRequest("$option.limit", 'limit', 14, 'int'); //I guess getUserStateFromRequest is for session or different reasons
$lim0 = JRequest::getVar('limitstart', 0, '', 'int');
$db->setQuery('SELECT SQL_CALC_FOUND_ROWS x, y, z FROM jos_content WHERE x',$lim0, $lim);
$rL=&$db->loadAssocList();
if (empty($rL)) {$jAp->enqueueMessage($db->getErrorMsg(),'error'); return;}
else {
////Here the beauty starts
$db->setQuery('SELECT FOUND_ROWS();'); //no reloading the query! Just asking for total without limit
jimport('joomla.html.pagination');
$pageNav = new JPagination( $db->loadResult(), $lim0, $lim );
foreach($rL as $r) {
//your display code here
}
echo $pageNav->getListFooter( ); //Displays a nice footer
You can see in their code that whilst they do use the db result, that the pagination doesn't 'depend' on the query. Only the results which come from it. So for the $db->loadResult() for example you can just use a php count forumla to see how many rows there are in the array being produced by the module. In your case counting the number of $items.
The foreach command is still as you have it as well. With just the foreach($rL as $r) just corresponding to the existing foreach($items as $item). So the fact you don't have the database query as you see - shouldn't actually be an issue!
So the code you want will be something like:
global $option; //If Joomla 1.5
global $mainframe; //If Joomla 2.5
$option = JRequest::getCmd('option') //If Joomla 2.5
$mainframe = JFactory::getApplication(); //If Joomla 2.5
$lim = $mainframe->getUserStateFromRequest("$option.limit", 'limit', 14, 'int'); //I guess getUserStateFromRequest is for session or different reasons
$lim0 = JRequest::getVar('limitstart', 0, '', 'int');
if (empty($items)) {
$app->enqueueMessage($db->getErrorMsg(),'error');
return;
} else {
jimport('joomla.html.pagination');
$pageNav = new JPagination( count($list), $lim0, $lim );
foreach($list as $item) {
//wrap in your code here that you had in the foreach already
}
echo $pageNav->getListFooter( ); //Displays a nice footer
Make sure you remove one of the top two lines depending on whether you're using Joomla 1.5 or 2.5 but that should work.
I have a array in controller I have to send it to view and then show the value
The Controller page code
public function showbookedmenu(){
$rowLength=$this->input->post('rowno');
$check=$this->input->post('checkeed');
$j=0;
for($i=1;$i<=$rowLength;$i++)
{
$check=$this->input->post('checkeed'.$i);
if($check== "checked")
{
$orderedItem[$j][$i] = $this->input->post('txtMenuItem'.$i);
$orderedItem[$j][$i+1] = $this->input->post('quantity'.$i);
$orderedItem[$j][$i+2] = $this->input->post('lebPrice'.$i);
$orderedItem[$j][$i+3]= $this->input->post('grandtotal'.$i);
$j++;
}
else{}
}
$data['order']= $orderedItem;
$this->load->view('orderpage', $data);
}
The view page
What will be the code??
First rewrite your controller action like this:
public function showbookedmenu()
{
$rowLength = $this->input->post('rowno');
$orderedItem = array();
for($i = 1; $i <= $rowLength; $i++)
{
$check = $this->input->post('checkeed'.$i);
if($check == "checked")
{
$orderedItem[] = array(
'menu_item' => $this->input->post('txtMenuItem'.$i),
'quantity' => $this->input->post('quantity'.$i),
'leb_price' => $this->input->post('lebPrice'.$i),
'grand_total' => $this->input->post('grandtotal'.$i)
);
}
}
$data['order'] = $orderedItem;
$this->load->view('orderpage', $data);
}
Then in your view you can do this:
<? foreach($order as $order_item): ?>
<? echo $order_item['menu_item']; ?>
<? echo $order_item['quantity']; ?>
<? echo $order_item['leb_price']; ?>
<? echo $order_item['grand_total']; ?>
<? endforeach; ?>
first try to print array value in your view file..
print_r($order);
if it is coming fine..
you can give it on
foreach ($order as $value):
and use it :
I'm newly working with CodeIgniter and PHP. I'm trying to do a simple task that is to show a multilevel menu. Let's say I have a student and status table. I want to show which students are under which status(senior, junior etc.). But I'm getting this error:
A PHP Error was encountered
Severity: Notice
Message: Trying to get property of non-object
Filename: views/sview.php
Line Number: 31
At line 31 i have
<?php echo $status->statusname;?>
The controller:
// ....
$data['status'] = $this->status_model->get_students();
$this->load->view('sview', $data);
The model:
function get_students(){
$s = $this->db->get('status');
foreach ($s->result() as $status){
$students = $this->db->get_where('student', array('status_id'=>$status->id));
$status->students = students->result();
}
return $s;
}
view:
<?php foreach($s as $status):?>
<h4><?php echo $status->statusname;?></h4>
<?php foreach($status->student as $student):?>
<?php echo $student->studentname; ?>
<?php endforeach;?>
<?php endforeach;?>
You're not modifying $s in the loop in get_students() so it is just returning the original query of all the records from the status table. You're also missing a '$' on the $students variable in your loop.
Try this your model:
function get_students()
{
$s = $this->db->get('status');
$statuses = array();
foreach ($s->result() as $status)
{
$students = $this->db->get_where('student', array('status_id'=>$status->id));
$status->students = $students->result();
$statuses[] = $status;
}
return $statuses;
}
That will return the modified $status variables in the $statuses array and then you can access them in your views.
Your controller is setting $data['status'] up with all the different statuses it looks like. Try changing the following in your view:
<?php foreach($status as $s):?>
<h4><?php echo $s->statusname;?></h4>
<?php foreach($s->student as $student):?>
<?php echo $student->studentname; ?>
<?php endforeach;?>
<?php endforeach;?>