How to assign a random display of items on a permanent basis. For example, out of 200 elements, I want only 3 elements to be displayed in random order, but when clearing the cache files, it returns to its original position. Look at my code
if (!function_exists('get_latest_products')) {
function get_latest_products($limit)
{
$ci =& get_instance();
$key = "latest_products";
if ($ci->default_location_id != 0) {
$key = "latest_products_location_" . $ci->default_location_id;
}
$latest_products = get_cached_data($key);
if (empty($latest_products)) {
$latest_products = $ci->product_model->get_products_limited($limit);
set_cache_data($key, $latest_products);
} else {
shuffle($latest_products);
$latest_products = array_slice($latest_products, 0, 3, TRUE);
}
return $latest_products;
}
}
Thank you all for your help. just had to delete the value "else"
Related
so i got imported my large excel file with huge informations with 1 sec and i did get all the information i need to display within 1 sec to , but i got a big probleme when displaying the array in the view coz i m testing if the cells are correct or not i m using 5 ifs and 3 foreach and it takes mote than 2 mins , i need help to display all the info in a short time this is my array , and thanks
and there is my code of the view which takes to much time to display infos
and thanks
//here we get our final result of true and false fields
$finale_array = [];
// here we get all our
$current_table2 = [];
$results_applied = [];
$current_result = [];
$columns = SCHEMA::getColumnListing('imports');
// here we get all our conditions
$conditions = DB::table('conditions')->select('number', 'field', 'value')->get();
// here we get all our data
$imports = DB::table('imports')->get();
$results = DB::table('results')->get();
$x = 0;
$default_value = 0;
foreach ($imports as $key => $imported) {
$res = get_object_vars($imported);
foreach ($conditions as $value) {
$array = get_object_vars($value);
$result = $this->test($columns, $array['field']); // the result of our test function
if ($result == "ok") {
if ($res[$array['field']] == $array['value']) {
foreach ($results as $value_result) {
$res_resultat = get_object_vars($value_result);
$test_field = $this->test($columns, $res_resultat['field']);
// testing if the condtion numder match with the result number
if (($res_resultat['condition_number'] == $array['number'])) {
if (($test_field == 'ok')) {
if ($res['id'] != $default_value) {
// here test if the difference between the id and the default value is different from the current id to insert
if (($res['id'] - $default_value) != $res['id']) {
array_push($current_table2, $results_applied);
array_push($finale_array, $current_table2);
$current_table2 = [];
$results_applied = [];
$default_value = $res['id'];
}
$current_table2 = [$res, $res['id']];
}
$current_result = [$res_resultat['field'], $res[$res_resultat['field']]];
if ($res_resultat['value'] == $res[$res_resultat['field']]) {
$current_result[2] = 'true';
$current_result[3] = $res_resultat['value'];
} else {
$current_result[2] = 'false';
$current_result[3] = $res_resultat['value'];
}
$current_result[4] = $array['number'];
array_push($results_applied, $current_result);
}
}
}
}
}
}
$default_value = $res['id'];
}
array_push($current_table2, $results_applied);
array_push($finale_array, $current_table2);
dd($finale_array);
return view('Appliedconditions', ['imports' => $finale_array, 'columns' => $columns]);
}
From what I can see, you are recovering all the data without paging it.
You must paginate the data using the paginate(#elements_per_page) directive in your query, where #elements_per_page is the number of elements you want to display per page.
For example:
$elements = Elements::select('*')->paginate(10);
and in your blade view you can retreive pagination links after the closing table tag in this way: {{ $elements->links() }}
I am getting the following error while trying to migrate. Actually, I have a lot of data so I used the chunk in laravel.
I am using MongoDB not SQL
** You must specify an orderBy clause when using this function.**
My migration file's up function is is
public function up()
{
ini_set('max_execution_time', 250);
ini_set('memory_limit', '1024M');
$product_array = DB::collection('product')->orderBy('created_at','asc');
$product_array->chunk(20, function($product_array)
{
$cotationPercentForecast=0;
$cotationPercent=0;
$quote_tpl = array();
foreach ($product_array as $key => $value) {
if (isset($value['quote_tpl'])) {
$quote_tpl = $value['quote_tpl'];
$defaultScoreCount = 0;
$realScoreCount = 0;
$forecastScoreCount = 0;
foreach ($quote_tpl as $idxPerimetre => $perimetre) {
if (isset($perimetre['families'])) {
foreach ($perimetre['families'] as $idxFamilies => $family) {
if (isset($family['subfamilies'])) {
foreach ($family['subfamilies'] as $idxSubFamilies => $subfamily) {
if (isset($subfamily['items'])) {
foreach ($subfamily['items'] as $idxitem => $item) {
if (isset($item['criterias'])) {
foreach ($item['criterias'] as $idxcriteria => $criteria) {
if (!isset($criteria['inactive']) || $criteria['inactive'] != 'true') {
$defaultScoreCount++;
if (isset($criteria['real_score'])) {
$realScoreCount++;
}
if (isset($criteria['forecast_score'])) {
$forecastScoreCount++;
}
}
} // FOREACH CRITERIA
} // ISSET CRITERIA ###
} // FOREACH ITEM
} // ISSET ITEM ###
} // FOREACH SUBFAMILY
} // ISSET SUBFAMILY ###
} // FOREACH FAMILY
} // ISSET FAMILY ###
}// FOREACH PERIMETER ##
if ($realScoreCount > 0 && $defaultScoreCount > 0) {
$cotationPercentUn = ($realScoreCount / $defaultScoreCount) * 100;
$cotationPercent = round($cotationPercentUn, 2);
}
if ($forecastScoreCount > 0 && $defaultScoreCount > 0) {
$cotationPercentUnForecast = ($forecastScoreCount / $defaultScoreCount) * 100;
$cotationPercentForecast = round($cotationPercentUnForecast, 2);
}
$results = DB::collection('product')->update(['cotation_percent' => $cotationPercent,'forecast_cotation_percent' => $cotationPercentForecast]);
}
}
});
}
I have gone through many answers here and almost all suggest to use orderBy so I used it. But still getting the error.
i have used
Product::chunk(5, function($product_array){}
Any help is appreciated. Thanks in advance.
This warning is added when Laravel internally uses enforceOrderBy which is defined inside Illuminate/Database/Query/Builder.
Whenever you use chunk on a query builder instantiated by DB facade Illuminate\Database\Query\Builder directly, it would ask you :
You must specify an orderBy clause when using this function.
So it will happen if you are doing :
\DB::table('product')->chunk(10, function($product){
...
});
If you manually add an order by to this, it will not throw the error and will work as expected :
\DB::table('product')->orderBy('created_at')->chunk(10, function($product){
...
});
However, its better to use the Eloquent Model directly like which will not enforce you to add an order by clause manually :
Product::chunk(10, function($product){
...
});
Also there is no method DB::collection(), you can use DB::table() instead if you wish, unless you are using mongodb and not MySQL
The orignial code was like this , I want to get landline_no value also in getRecords, How to do that
public function checklead() {
$lead = $_POST['number'];
$check = $this->common_model->getRecords('leads',array("phone_no"=>$lead));
if(count($check) > 0) {
$lead = $this->common_model->getRecored_row('leads',array("phone_no"=>$lead));
if($lead->assignto_self != 0) {
$assignto = $lead->assignto_self;
$key = 'Self Assign';
} else if($lead->assignto_se != 0) {
$assignto = $lead->assignto_se;
$key = '';}
What I have achieved so far,but not getting array values from getRecords
$lead = $_POST['number'];
$check = $this->common_model->getRecords('leads',array("phone_no"=>$lead),array("landline_no"=>$lead));
//echo "<pre>";
//print_r($check);
//echo $check[0]['landline_no'];exit;
if(count($check) > 0) {
$lead = $this->common_model->getRecored_row('leads',array("phone_no"=>$lead,"landline_no"=>$check[0]['landline_no']));
Code for getRecords:
function getRecords($table,$db = array(),$select = "*",$ordercol = '',$group = '',$start='',$limit=''){
$this->db->select($select);
if(!empty($ordercol)){
$this->db->order_by($ordercol);
}
if($limit != '' && $start !=''){
$this->db->limit($limit,$start);
}
if($group != ''){
$this->db->group_by($group);
}
$q=$this->db->get_where($table, $db);
return $q->result_array();
}
// Get Recored row
public function getRecored_row($table,$where)
{
$q = $this->db->where($where)
->select('*')
->get($table);
return $q->row();
}
Check my answer: This code also working well, i have written, but i am not sure , this logic is correct or not kindly check this one.
public function checklead() {
$lead = $_POST['number'];
if($this->common_model->getRecords('leads',array("phone_no"=>$lead)))
{
$check=$this->common_model->getRecords('leads',array("phone_no"=>$lead));
}
else
{
$check=$this->common_model->getRecords('leads',array("landline_no"=>$lead));
}
echo "<pre>";
//echo $check;
//print_r($check); exit;
$p= $check[0]['phone_no'];
$l= $check[0]['landline_no'];
// exit;
if(count($p) > 0 || count($l)>0) {
$lead = $this->common_model->getRecored_row('leads',array("phone_no"=>$p));
$lead1 = $this->common_model->getRecored_row('leads',array("landline_no"=>$l));
if($lead->assignto_self != 0 || $lead1->assignto_self != 0) {
$assignto = $lead->assignto_self;
$key = 'Self Assign';
} else if($lead->assignto_se != 0 || $lead1->assignto_se != 0) {
$assignto = $lead->assignto_se;
$key = '';
}else if($lead->assignto_tl != 0 || $lead1->assignto_tl != 0) {
$assignto = $lead->assignto_tl;
$key = '';
} else if($lead->uploaded_by != 0 || $lead1->uploaded_by != 0) {
$assignto = $lead->uploaded_by;
$key = 'Uploaded by';
}
$user = $this->common_model->getRecored_row('admin',array("id"=>$assignto));
$role = $this->common_model->getRecored_row('role',array("id"=>$user->role));
$this->session->set_flashdata('message', array('message' => 'This Lead Already exist with '.$user->name.' ('.$role->role.') '.' ','class' => 'danger'));
redirect(base_url().'leads');
} else {
redirect(base_url().'leads/add_newlead/'.$lead);
}
}
There does not seem to be any reason to use getRecords(). The $check value has no useful purpose and creating it is a waste of resources.
We don't need $check because getRecord_row() will return the "lead" if found so the only check needed is to see if getRecord_row() returns anything. getRecord_row() uses the database function row() which returns only one row or null if no rows are found. Read about row() here.
If what you want is to find the "lead" that has either a "phone_no" or a "landline_no" equal to $_POST['number'] then you need to use a custom string for the where clause. (See #4 at on this documentation page.) You need a custom string because getRecord_row() does not allow any other way to ask for rows where a='foo' OR b='foo'. Here is what I think you are looking for.
public function checklead()
{
// use input->post() it is the safe way to get data from $_POST
$phone = $this->input->post('number');
// $phone could be null if $_POST['number'] is not set
if($phone)
{
$lead = $this->common_model->getRecored_row('leads', "phone_no = $phone OR landline_no = $phone");
// $lead could be null if nothing matches where condition
if($lead)
{
if($lead->assignto_self != 0)
{
$assignto = $lead->assignto_self;
$key = 'Self Assign';
}
else if($lead->assignto_se != 0)
{
$assignto = $lead->assignto_se;
$key = '';
}
}
}
}
The main difference between getRecords() and getRecord_row() is the number of records (rows of data) to return. getRecord_row() will return a maximum of one record while getRecords() might return many records.
getRecords() accepts arguments that allow control of what data is selected ($db, $select), how it is arranged ($ordercol, $group), and the number of rows to retrieve ($limit) starting at row number x ($start) .
I want to add values from Custom Attribute to short description of Configurable Product in Magento. I am using SCP module to show dynamically short description, title and price for this one regarding to "Associated Simple Products ". The price, Title and short description work fine but it not change the long description and not show the custom Attributes associated to Simple product.
Can some body help me with this problem? I need some indication how can I do that?
I think that I can do it on the original file configurable.php from SCP (Simple Configurable products) module that I attached to this post but I am not sure.
Thank you in advance.
public function getJsonConfig()
{
$config = Zend_Json::decode(parent::getJsonConfig());
$childProducts = array();
//Create the extra price and tier price data/html we need.
foreach ($this->getAllowProducts() as $product) {
$productId = $product->getId();
$childProducts[$productId] = array(
"price" => $this->_registerJsPrice($this->_convertPrice($product->getPrice())),
"finalPrice" => $this->_registerJsPrice($this->_convertPrice($product->getFinalPrice()))
);
if (Mage::getStoreConfig('SCP_options/product_page/change_name')) {
$childProducts[$productId]["productName"] = $product->getName();
}
if (Mage::getStoreConfig('SCP_options/product_page/change_description')) {
$childProducts[$productId]["description"] = $product->getDescription();
}
if (Mage::getStoreConfig('SCP_options/product_page/change_short_description')) {
$childProducts[$productId]["shortDescription"] = $product->getShortDescription();
}
if (Mage::getStoreConfig('SCP_options/product_page/change_attributes')) {
$childBlock = $this->getLayout()->createBlock('catalog/product_view_attributes');
$childProducts[$productId]["productAttributes"] = $childBlock->setTemplate('catalog/product/view/attributes.phtml')
->setProduct($product)
->toHtml();
}
#if image changing is enabled..
if (Mage::getStoreConfig('SCP_options/product_page/change_image')) {
#but dont bother if fancy image changing is enabled
if (!Mage::getStoreConfig('SCP_options/product_page/change_image_fancy')) {
#If image is not placeholder...
if($product->getImage()!=='no_selection') {
$childProducts[$productId]["imageUrl"] = (string)Mage::helper('catalog/image')->init($product, 'image');
}
}
}
}
//Remove any existing option prices.
//Removing holes out of existing arrays is not nice,
//but it keeps the extension's code separate so if Varien's getJsonConfig
//is added to, things should still work.
if (is_array($config['attributes'])) {
foreach ($config['attributes'] as $attributeID => &$info) {
if (is_array($info['options'])) {
foreach ($info['options'] as &$option) {
unset($option['price']);
}
unset($option); //clear foreach var ref
}
}
unset($info); //clear foreach var ref
}
$p = $this->getProduct();
$config['childProducts'] = $childProducts;
if ($p->getMaxPossibleFinalPrice() != $p->getFinalPrice()) {
$config['priceFromLabel'] = $this->__('Price From:');
} else {
$config['priceFromLabel'] = $this->__('');
}
$config['ajaxBaseUrl'] = Mage::getUrl('oi/ajax/');
$config['productName'] = $this->getProduct()->getName();
$config['description'] = $this->getProduct()->getDescription();
$config['shortDescription'] = $this->getProduct()->getShortDescription();
if (Mage::getStoreConfig('SCP_options/product_page/change_image')) {
$config["imageUrl"] = (string)Mage::helper('catalog/image')->init($this->getProduct(), 'image');
}
$childBlock = $this->getLayout()->createBlock('catalog/product_view_attributes');
$config["productAttributes"] = $childBlock->setTemplate('catalog/product/view/attributes.phtml')
->setProduct($this->getProduct())
->toHtml();
if (Mage::getStoreConfig('SCP_options/product_page/change_image')) {
if (Mage::getStoreConfig('SCP_options/product_page/change_image_fancy')) {
$childBlock = $this->getLayout()->createBlock('catalog/product_view_media');
$config["imageZoomer"] = $childBlock->setTemplate('catalog/product/view/media.phtml')
->setProduct($this->getProduct())
->toHtml();
}
}
if (Mage::getStoreConfig('SCP_options/product_page/show_price_ranges_in_options')) {
$config['showPriceRangesInOptions'] = true;
$config['rangeToLabel'] = $this->__('to');
}
//Mage::log($config);
return Zend_Json::encode($config);
//parent getJsonConfig uses the following instead, but it seems to just break inline translate of this json?
//return Mage::helper('core')->jsonEncode($config);
}
I was reading this article on Wikipedia and stumbled on the line which says "trie is also called prefix tree".
I know the usage of trie but why is it called "prefix tree"?
As they can be searched by prefixes. You can also reverse the trie and find wildcards: http://phpir.com/tries-and-wildcards.
For example the term academic would be c-i-m-e-d-a-c-a. Using the same
technique as before we can now search for all words that end with a
certain phrase, allowing us to handle wildcards at the beginning of
query terms, e.g. *cademically.
<?php
function buildTries($words) {
$trie = new Trie();
$rtrie = new Trie();
foreach($words as $word) {
$trie->add($word);
$rtrie->add(strrev($word));
}
return array('trie' => $trie, 'rtrie' => $rtrie);
}
function searchTries($search, $tries) {
$terms = explode('*', $search);
if(count($terms) > 2) {
return false;
}
if(strlen($terms[0]) && strlen($terms[0])) {
// middle wildcard
$straight = $tries['trie']->prefixSearch($terms[0]);
$rev = $tries['rtrie']->prefixSearch(strrev($terms[1]));
return array_intersect($straight, reverseArray($rev));
} else if(strlen($terms[1]) ) {
// leading wildcard
return reverseArray($tries['rtrie']->prefixSearch(strrev($terms[1])));
} else {
// trailing wildcard
return $tries['trie']->prefixSearch($terms[0]);
}
}
function reverseArray($keys) {
$return = array();
foreach($keys as $key => $value) {
$return[strrev($key)] = $value;
}
return $return;
}
/* Do some searches */
$words = array(
'adder',
'addled',
'abject',
'agreement',
'astronaut',
'handily',
'happily',
'helpfully'
);
$tries = buildTries($words);
$return = searchTries('h*ly', $tries);
var_dump($return);
$return = searchTries('ha*ly', $tries);
var_dump($return);
?>
The results from the two var dumps look like this:
array(3) {
["handily"]=>
NULL
["happily"]=>
NULL
["helpfully"]=>
NULL
}
array(2) {
["handily"]=>
NULL
["happily"]=>
NULL
}