How to shuffle an array and then slice it - php

I have a problem with shuffling and slicing array.
I have this code:
$maxDisplayItem = $this->_getFlexformConfig('max_item_to_display', 'product_setting');
$selectedProducts = array_slice($selectedProducts, 0, $maxDisplayItem);
foreach ($selectedProducts as $_id) {
shuffle($products);
foreach ($products as $_product) {
....
}
}
My code limiting the number of displayed item but didn't shuffle it at all.
When I change the order of actions:
shuffle($selectedProducts);
foreach ($selectedProducts as $_id) {
$maxDisplayItem = $this->_getFlexformConfig('max_item_to_display', 'product_setting');
$products = array_slice($products, 0, $maxDisplayItem);
foreach ($products as $_product) {
....
}
}
the code shuffling and slicing results but only first (e.g. 3 results) from whole array who has 50 items.
Could anyone help me with this?
here is the whole function:
function displayProductList()
{
// Store View
$store = $this->getStoreViewCode();
$selectedProducts = $this->getSelectedProducts();
$products = $this->_products->getProductsFromDb($selectedProducts, $store, $this->getProductsStoragePid());
// Load Template File
$templateHtml = $this->cObj->fileResource( $this->_getConfig('templateProductList') );
$productListHtml = $this->cObj->getSubpart($templateHtml, '###PRODUCT_LIST###');
$productHtml = $this->cObj->getSubpart($productListHtml, '###PRODUCT_ITEM###');
$subPartContent = ''; $item = 0; $items = count($products); $even = true; $line = '';
shuffle($selectedProducts);
foreach ($selectedProducts as $_id) {
$maxDisplayItem = $this->_getFlexformConfig('max_item_to_display', 'product_setting');
$products = array_slice($products, 0, $maxDisplayItem);
foreach ($products as $_product) {
if ($_id === $_product['product_id']) {
$markers = $this->_products->getProductMarkers($_product);
// Even/Odd CSS Class Determination
if ($even === true) {
$line = 'even';
$even = false;
} else {
$line = 'odd';
$even = true;
}
// Class Determination First/Last
if ($item == 0) {
$markers['###EVENODD###'] = $line . ' ' . 'first';
} else if ($item == $items-1) {
$markers['###EVENODD###'] = $line . ' ' . 'last';
} else {
$markers['###EVENODD###'] = $line;
}
// Check if the product has an image
$imageHtml = '<p>'.$this->pi_getLL('template_label_no_image_available').'</p>';
if ($markers['###DETAIL_IMAGE###'] != 'no_selection') {
$imageHtml = $this->cObj->getSubpart($productHtml, '###PRODUCT_IMAGE###');
}
$p = $this->cObj->substituteSubpart($productHtml, '###PRODUCT_IMAGE###', $imageHtml);
$subPartContent .= $this->cObj->substituteMarkerArray($p, $markers);
$item++;
}
}
}
return $this->cObj->substituteSubpart($productListHtml, '###PRODUCT_ITEM###', $subPartContent);
}

function displayProductList(){
// Store View
$store = $this->getStoreViewCode();
$selectedProducts = $this->getSelectedProducts();
$products = $this->_products->getProductsFromDb($selectedProducts, $store, $this->getProductsStoragePid());
// Load Template File
$templateHtml = $this->cObj->fileResource( $this->_getConfig('templateProductList') );
$productListHtml = $this->cObj->getSubpart($templateHtml, '###PRODUCT_LIST###');
$productHtml = $this->cObj->getSubpart($productListHtml, '###PRODUCT_ITEM###');
$subPartContent = ''; $item = 0; $items = count($products); $even = true; $line = '';
$maxDisplayItem = $this->_getFlexformConfig('max_item_to_display', 'product_setting');
$products = array_slice($products, 0, $maxDisplayItem);
shuffle($products);
foreach ($products as $_product) {
$markers = $this->_products->getProductMarkers($_product);
// Even/Odd CSS Class Determination
if ($even === true) {
$line = 'even';
$even = false;
} else {
$line = 'odd';
$even = true;
}
// Class Determination First/Last
if ($item == 0) {
$markers['###EVENODD###'] = $line . ' ' . 'first';
} else if ($item == $items-1) {
$markers['###EVENODD###'] = $line . ' ' . 'last';
} else {
$markers['###EVENODD###'] = $line;
}
// Check if the product has an image
$imageHtml = '<p>'.$this->pi_getLL('template_label_no_image_available').'</p>';
if ($markers['###DETAIL_IMAGE###'] != 'no_selection') {
$imageHtml = $this->cObj->getSubpart($productHtml, '###PRODUCT_IMAGE###');
}
$p = $this->cObj->substituteSubpart($productHtml, '###PRODUCT_IMAGE###', $imageHtml);
$subPartContent .= $this->cObj->substituteMarkerArray($p, $markers);
$item++;
}
return $this->cObj->substituteSubpart($productListHtml, '###PRODUCT_ITEM###', $subPartContent);
}

Related

Codeigniter 3 | set limit display records in foreach

in view I can fetch all categories:
<?php foreach ($this->parent_categories as $category): ?>
<?php endforeach ?>
Now controller:
$data['parent_categories'] = $this->category_model->get_parent_categories_tree($category);
and finally model category:
//get parent categories tree
public function get_parent_categories_tree($category, $only_visible = true)
{
if (empty($category)) {
return array();
}
//get cached data
$key = "parent_categories_tree_all";
if ($only_visible == true) {
$key = "parent_categories_tree";
}
$key = $key . "_lang_" . $this->selected_lang->id;
$result_cache = get_cached_data($this, $key, "st");
if (!empty($result_cache)) {
if (!empty($result_cache[$category->id])) {
return $result_cache[$category->id];
}
} else {
$result_cache = array();
}
$parent_tree = $category->parent_tree;
$ids = array();
$str_sort = "";
if (!empty($parent_tree)) {
$array = explode(',', $parent_tree);
if (!empty($array)) {
foreach ($array as $item) {
array_push($ids, intval($item));
if ($str_sort == "") {
$str_sort = intval($item);
} else {
$str_sort .= "," . intval($item);
}
}
}
}
if (!in_array($category->id, $ids)) {
array_push($ids, $category->id);
if ($str_sort == "") {
$str_sort = $category->id;
} else {
$str_sort .= "," . $category->id;
}
}
$this->build_query($this->selected_lang->id, true);
$this->db->where_in('categories.id', $ids, FALSE);
if ($only_visible == true) {
$this->db->where('categories.visibility', 1);
}
$this->db->order_by('FIELD(id, ' . $str_sort . ')');
$result = $this->db->get('categories')->result();
$result_cache[$category->id] = $result;
set_cache_data($this, $key, $result_cache, "st");
return $result;
}
but the problem is currently I fetch with this code all categories without limit. How to get first 10 records?
I try:
$result = $this->db->get('categories', 10)->result();
But this not work and still fetch all categories. Can anyone help me resolve this issue? Maybe I do something wrong. Thanks for check.

Insert element into an array in PHP

foreach($key_doc_count as $item) {
mb_language('Japanese');
$product = $item["key"];
$product_url = 'https://search.rakuten.co.jp/search/mall/'.urlencode($product) . '/';
$source = file_get_contents($product_url);
$source = mb_convert_encoding($source, 'utf8', 'auto');
$rakuten_search_html = str_get_html($source);
$count=0;
foreach ($rakuten_search_html->find('img._verticallyaligned') as $item_image) {
if(strlen($item_image->alt > 2))
{
$ss['image_url'] = $item_image->src;
$ss['title'] = $item_image->alt;
$items_kk[] = $ss;
$count++;
if($count <5)
{
break;
}
}
}
$new_item["term"] = $item["key"];
$new_item["current_count"] = $item["doc_count"];
$new_item["results"] = $terms_kk;
$new_word_array[] = $new_item;
}
var_dump($new_word_array);
I am trying to insert the url and title of the product in an array names $ss and then assign that array to $new_term["result"] .
But its not working
The error was HTTP ERROR 500
The variables $items_kk and $new_word_array seems to have not been initialized outside of the foreach loop. Try to init them as an empty array just before the loop :
$new_word_array = [];
foreach($key_doc_count as $item) {
mb_language('Japanese');
$product = $item["key"];
$product_url = 'https://search.rakuten.co.jp/search/mall/'.urlencode($product) . '/';
$source = file_get_contents($product_url);
$source = mb_convert_encoding($source, 'utf8', 'auto');
$rakuten_search_html = str_get_html($source);
$count=0;
$items_kk = [];
foreach ($rakuten_search_html->find('img._verticallyaligned') as $item_image) {
if(strlen($item_image->alt > 2))
{
$ss['image_url'] = $item_image->src;
$ss['title'] = $item_image->alt;
$items_kk[] = $ss;
$count++;
if($count <5)
{
break;
}
}
}
$new_item["term"] = $item["key"];
$new_item["current_count"] = $item["doc_count"];
$new_item["results"] = $terms_kk;
$new_word_array[] = $new_item;
}
var_dump($new_word_array);
Also, you're setting $items_kk and assigning $terms_kk to the new array. It may be an error ?

How to Update Categories that Already Exists in Magento Database Using Custom Script

I have Already Created The Categories in Magento by using the custom script,
but issue is when I again run the same URL my script creates another set of same category. as i want to update the existing category and insert the new categories if exist in the csv.
My csv structure is:
Category 1,Description,Category 2,Description,Category 3,Description,Category 4,Description
1,COSTUMES,1,ADULTS,1,MENS
1,COSTUMES,1,ADULTS,1,MENS,2,ASIAN
1,COSTUMES,1,ADULTS,1,MENS,3,BIKER
1,COSTUMES,1,ADULTS,1,MENS,1,CAPES & ROBES
1,COSTUMES,1,ADULTS,1,MENS,5,CAVE PEOPLE
Thanking All of You in Advance For Your Answer
Below is my code to create multi level categories:
define('MAGENTO', realpath(dirname(__FILE__)));
require_once MAGENTO . '/app/Mage.php';
umask(0);
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
$count = 0;
$file = fopen('export/web categories.csv', 'r');
function odd($var)
{
$odd = array();
foreach ($var as $k => $v) {
if ($k % 2 !== 0) {
$odd[$k] = $v;
}
}
return $odd;
}
function even($var)
{
$even = array();
foreach ($var as $k => $v) {
if ($k % 2 == 0) {
$even[$k] = $v;
}
}
return $even;
}
function strcount($str,$sy){
$ch= explode($sy, $str);
return count($ch);
}
$pos=0;
$row_config= array();
$test=array();
$catgoryID=array();
$parID = 1;
while (($line = fgetcsv($file)) !== FALSE) {
if(!in_array($valtest,$row_config)){
if($count == 0){
$count++;
continue;
}
$count++;
$filterd_data=array_filter($line);
$odd_cell_data=odd($filterd_data);
$even_cell_data=even($filterd_data);
$config=array();
$string='';
$intialID=$even_cell_data[0];
foreach($odd_cell_data as $key=>$val){
if(!in_array($val,$config)){
$config[] = $val;
$data['general']['name'] =$val;
$data['general']['meta_title'] = "";
$data['general']['meta_description'] = "";
$data['general']['is_active'] = "";
$data['general']['url_key'] = "";
$data['general']['is_anchor'] = 0;
$data['general']['position'] =1 ;
$storeId = 0;
$string .=$val.'~';
if(!array_key_exists($string, $row_config)){
$catID=createCategory($data, $storeId);
$catgoryID[$string]=$catID;
$row_config[$string]=$parID;
} else {
$parID =$row_config[$string] ;
$row_config[$string]=$row_config[$string];
}
if( strcount($string,'~')==2){
$parID=1;
}
$int[$string]=$parID;
assignCat($catgoryID[$string],$parID);
$parID = $catgoryID[$string];
sleep(0.5);
unset($data);
}
}
}
}
//This Function is used for create each category
function createCategory($data, $storeId) {
$category = Mage::getModel('catalog/category');
$category->setStoreId($storeId);
if (is_array($data)) {
$category->addData($data['general']);
if (!$category->getId()) {
$parentId = $data['category']['parent'];
if (!$parentId) {
if ($storeId) {
$parentId = Mage::app()->getStore($storeId)->getRootCategoryId();
} else {
$parentId = Mage_Catalog_Model_Category::TREE_ROOT_ID;
}
}
$parentCategory = Mage::getModel('catalog/category')->load($parentId);
$category->setPath($parentCategory->getPath());
} if ($useDefaults = $data['use_default']) {
foreach ($useDefaults as $attributeCode) {
$category->setData($attributeCode, null);
}
}
$category->setAttributeSetId($category->getDefaultAttributeSetId());
if (isset($data['category_products']) && !$category->getProductsReadonly()) {
$products = array();
parse_str($data['category_products'], $products);
$category->setPostedProducts($products);
} try {
$category->save();
$category = Mage::getModel('catalog/category')->load($category->getId());
$category->setPosition($data['general']['position']);
$category->addData($data['general']);
$category->save();
echo "Suceeded <br /> ";
} catch (Exception $e) {
echo "Failed <br />";
}
}
return $category->getId();
}
//This Function is used for moving category under respective parent
function assignCat($id, $parent){
$category = Mage::getModel( 'catalog/category' )->load($id);
Mage::unregister('category');
Mage::unregister('current_category');
Mage::register('category', $category);
Mage::register('current_category', $category);
$category->move($parent);
return;
}

How can i turn these into groups of 4 instep of 2?

So this is my code it takes a list o people from the database and lists them with their partners in groups. Within these groups, the user id of the people cannot appear in the same row twice. Everything works, Im just wondering how to make it echo 4 people per group versus only 2.
if ($result = $mysqli->query("SELECT * FROM performers")) {
printf("Found %d rows.\n", $result->num_rows);
$rows = array();
while ($row = $result->fetch_array()) {
foreach ($row as $key => $col) {
unset($row[$key]);
$row[strtolower($key)] = $col;
}
$rows[] = $row;
}
$current = null;
$count = 1;
while ( ! empty($rows)) {
if ($current) {
$current_performers = array($current['performerid_1'], $current['performerid_2']);
$found = false;
foreach ($rows as $key => $row) {
if ( ! in_array($row['performerid_1'], $current_performers) && ! in_array($row['performerid_2'], $current_performers)) {
$found = $key;
break;
}
}
if ($found !== false) {
echo '<li>', $rows[$found]['performance_id'], ': ', $rows[$found]['perf_name_1'], ' - ', $rows[$found]['perf_name_2'], '</li>';
unset($rows[$key]);
}
else {
echo '';
}
echo '</ul><hr />';
$current = null;
} else {
$current = array_shift($rows);
echo '<h3>Group ', $count+, '</h3>';
echo '<ul>';
echo '<li>', $current['performance_id'], ': ', $current['perf_name_1'], ' - ', $current['perf_name_2'], '</li>';
}
}
I think this should do it, but I haven't tested it (except to verify syntax) because I don't have any sample data.
$group_size = 4;
$current_performers = array();
$current_size = 0;
$count = 1;
while (!empty($rows)) {
if ($current_size == $group_size) { // End previous group
echo '</ul><hr>';
$current_performers = array();
$current_size = 0;
}
if ($current_size == 0) {
echo '<h3>Group ', $count++, '</h3>';
echo '<ul>';
}
$found = false;
foreach ($rows as $key => $row) {
if ( ! in_array($row['performerid_1'], $current_performers) && ! in_array($row['performerid_2'], $current_performers)) {
$found = true;
array_push($current_performers, $row['performerid_1'], $row['performerid_2']);
$current_size++;
echo '<li>', $row['performance_id'], ': ', $row['perf_name_1'], ' - ', $row['perf_name_2'], '</li>';
unset($rows[$key]);
break;
}
}
if (!$found) {
// Force a new group to start
$current_size = $group_size;
}
// If we have an unfinished group, finish it
if ($current_size) {
echo '</ul><hr>';
}
}

using script "RSSlib "(php) how can I sort items in RSS feed so oldest shows first?

I have two pages, one is the script itself, and the other the page that calls it. I can display my feed fine, but I need to display it in reverse order. (oldest first). I have tried the two asort and arsort functions, but I cant get them to work.
Here is the code:
$RSS_Content = array();
function RSS_Tags($item, $type)
{
$y = array();
$tnl = $item->getElementsByTagName("title");
$tnl = $tnl->item(0);
$title = $tnl->firstChild->data;
$tnl = $item->getElementsByTagName("link");
$tnl = $tnl->item(0);
$link = $tnl->firstChild->data;
//$tnl = $item->getElementsByTagName("description");
// $tnl = $tnl->item(0);
// $description = $tnl->firstChild->data;
$y["title"] = $title;
$y["link"] = $link;
//$y["description"] = $description;
$y["type"] = $type;
return $y;
}
function RSS_Channel($channel)
{
global $RSS_Content;
$items = $channel->getElementsByTagName("item");
// Processing channel
$y = RSS_Tags($channel, 0); // get description of channel, type 0
array_push($RSS_Content, $y);
// Processing articles
foreach($items as $item)
{
$y = RSS_Tags($item, 1); // get description of article, type 1
array_push($RSS_Content, $y);
}
}
function RSS_Retrieve($url)
{
global $RSS_Content;
$doc = new DOMDocument();
$doc->load($url);
$channels = $doc->getElementsByTagName("channel");
$RSS_Content = array();
foreach($channels as $channel)
{
RSS_Channel($channel);
}
}
function RSS_RetrieveLinks($url)
{
global $RSS_Content;
$doc = new DOMDocument();
$doc->load($url);
$channels = $doc->getElementsByTagName("channel");
$RSS_Content = array();
foreach($channels as $channel)
{
$items = $channel->getElementsByTagName("item");
foreach($items as $item)
{
$y = RSS_Tags($item, 1); // get description of article, type 1
array_push($RSS_Content, $y);
}
}
}
function RSS_Links($url, $size)
{
global $RSS_Content;
$page = "<ul>";
RSS_RetrieveLinks($url);
if($size > 0)
$recents = array_slice($RSS_Content, 0, $size);
foreach($recents as $article)
{
$type = $article["type"];
if($type == 0) continue;
$title = $article["title"];
$link = $article["link"];
$page .= "<li>$title</li>\n";
}
$page .="</ul>\n";
return $page;
}
function RSS_Display($url, $size)
{
global $RSS_Content;
asort($RSS_Content);
$opened = false;
$page = "";
RSS_Retrieve($url);
if($size > 0)
$recents = array_slice($RSS_Content, 0, $size);
foreach($recents as $article)
{
$type = $article["type"];
if($type == 0)
{
if($opened == true)
{
$page .="</ul>\n";
$opened = false;
}
$page .="<b>";
}
else
{
if($opened == false)
{
$page .= "<ul>\n";
$opened = true;
}
}
$title = $article["title"];
$link = $article["link"];
// $description = $article["description"];
$page .= "<p>$title";
// if($description != false)
{
//$page .= "<br>$description";
}
$page .= "</p>\n";
if($type==0)
{
$page .="</b><br />";
}
}
if($opened == true)
{
$page .="</ul>\n";
}
return $page."\n";
}
Then on the second page, I have this:
$url = "feedurlhere.xml";
echo RSS_Links($url, 10);
?>
</div>
Thanks to Scriptol, the answer is:
change all instances of array_push to array_switch
Cheers

Categories