PHP recursive function Bad Gateway - php

I have 2 function in a Class, one is a recursive function.
public static function _itemsByParent($categories, $parentId) {
$out = array();
foreach($categories as $category) {
if(empty($category['parent']) && $parentId == 0)
$out[] = $category;
elseif($category['parent'] == $parentId)
$out[] = $category;
}
return (empty($out) ? false : $out);
}
public static function loopOnLevels($input, $parent=0) {
$categories = self::_itemsByParent($input, $parent);
$out = null;
if($categories !== false) {
$i = 0;
$out = '<ul>';
foreach($categories as $category) {
$out .= '<li>'.$category['name_hu'];
$childs = self::loopOnLevels($input, $category['category_id']);
if($childs !== false) {
$out .= $childs;
}
$out .= '</li>';
$i++;
}
$out .= '</ul>';
}
return (empty($out) ? false : $out);
}
I pass a simple array and parent is null at start:
$o = self::loopOnLevels($categoriesTransformed, 0);
My array looks like: http://screencloud.net/v/10sq
....
Why I get 502 Bad Gateway.
Maybe infinite loop? But why?

Related

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;
}

Category Hierarchy with Selected and Disable Mode (PHP-MySQL)

I use this code to make dropdown list like this, support selected parent when update mode
Current category dropdown (select category 1.1 a child of category 1)
public static function dropdown($parent, $child = null) {
static $level = 0;
static $return = '';
$search = self::all(array('parent' => $parent, 'status' => 1));
foreach ($search as $data) {
$level--;
$space = '';
for($i = 1; $i < ($level*-1); $i++) $space .= ' ';
if ($child == $data->id) $selected = 'selected';
else $selected = '';
$return .= '<option value="'.$data->id.'" '.$selected.'>'.$space.'- '.$data->name.'</option>';
self::dropdown($data->id, $child);
$level++;
}
return $return;
}
Problem : How to disable all child of category 1.1 and him self when i update category 1.1 ??
Goal screenshot :
try this :
public static function dropdown($parent, $child = null, $isSelected=false) {
static $level = 0;
static $return = '';
$search = self::all(array('parent' => $parent, 'status' => 1));
foreach ($search as $data) {
$level--;
$space = '';
for($i = 1; $i < ($level*-1); $i++) $space .= ' ';
if ($child == $data->id || $isSelected){
$selected = 'selected';
$isSelected = true;
}else{
$selected = '';
}
$return .= '<option value="'.$data->id.'" '.$selected.'>'.$space.'- '.$data->name.'</option>';
self::dropdown($data->id, $child, $isSelected);
$level++;
}
return $return;
}
Basically you have to transfer the status (selected or not) of the current node, and transfers it to his childs.

Only variables should be passed by reference in

I inherited maintenance of a Drupal 7 website and I have zero PHP experience and I need some help. I have just updated Drupal to 7.31 and am getting the error "Only variables should be passed by reference in..." on lines 43 and 86 of an .inc file.
Here is line 43:
$item = array_shift(array_values($data));
Here is line 86:
$item = array_shift(array_values($data));
Can anyone help me out?
I don't know if this is allowed but here the code for the .inc file
<?php
$plugin = _cdd_core_content_type_plugin('nauticus_core', 'menu_full_leaf', 'Page: menu leaf', array(
'description' => 'Add menu children',
), array(
'override_title' => 1,
'override_title_text' => ''
), 'Sail Nauticus');
function nauticus_core_menu_full_leaf_content_type_plugin_render($subtype, &$conf, $panel_args) {
$trail = menu_get_active_trail();
$menu = '';
if (is_array($trail)) {
$leaf = array_pop($trail);
if (isset($leaf['menu_name'])) {
$menu_name = $leaf['menu_name'];
if ($menu_name !== 'navigation') {
$depth = $leaf['depth'];
$p1 = $leaf['p1'];
$data = menu_tree_page_data($menu_name, $depth + 1);
foreach ($data as $i => $item) {
if ($item['link']['mlid'] !== $leaf['plid']
&& !($leaf['plid'] == 0 && ($item['link']['mlid'] == $leaf['mlid']))
) {
unset($data[$i]);
}
}
if (sizeof($data) > 1) {
$menu = menu_tree_output($data);
foreach ($menu as $i => $item) {
if (isset($item['#original_link'])) {
if ($item['#original_link']['mlid'] !== $p1) {
if (isset($menu[$i]['#below'])) {
$menu[$i]['#below'] = array();
}
}
}
}
}
elseif (sizeof($data) == 1) {
$item = array_shift(array_values($data));
if (isset($item['below']) && !empty($item['below'])) {
$menu = menu_tree_output($item['below']);
foreach ($menu as $i => $item) {
if (isset($item['#original_link'])) {
if ($item['#original_link']['mlid'] !== $p1) {
if (isset($menu[$i]['#below'])) {
$menu[$i]['#below'] = array();
}
}
}
}
}
}
}
}
}
return $menu;
}
function nauticus_core_menu_full_leaf_content_type_plugin_title($subtype, &$conf, $panel_args) {
$title = 'Navigation';
$trail = menu_get_active_trail();
if (is_array($trail)) {
$leaf = array_pop($trail);
if (isset($leaf['menu_name'])) {
$menu_name = $leaf['menu_name'];
if ($menu_name !== 'navigation') {
$depth = $leaf['depth'];
$p1 = $leaf['p1'];
$data = menu_tree_page_data($menu_name, $depth + 1);
foreach ($data as $i => $item) {
if ($item['link']['mlid'] !== $leaf['plid']
&& !($leaf['plid'] == 0 && ($item['link']['mlid'] == $leaf['mlid']))
) {
unset($data[$i]);
}
}
if (sizeof($data) >= 1) {
$item = array_shift(array_values($data));
if (isset($item['link']) && !empty($item['link'])) {
if (isset($item['link']['link_title'])) {
$title = $item['link']['link_title'];
}
}
}
}
}
}
return $title;
}
array_shift requires that the first argument be a pass by reference and array_values returns an array.
change those lines that you have $item = array_shift(array_values($data)); to
$item = array_values($data);
$item = array_shift(&$item);
the & means the variable is pass by reference. This should fix your problem.
if that does not work just remove the &.
Change
$item = array_shift(array_values($data));
to
$tmp = array_values($data);
$item = array_shift($tmp);

Build tree from parent_id id table structure

I'm trying to build a tree with the exact specifications of..
This Question
Basically I need to create a tree from a parent - id table structure.
I'm using this function to try to achieve the above;
private static function fetch_recursive($src_arr, $currentid = 0, $parentfound = false, $cats = array())
{
foreach($src_arr as $row)
{
if((!$parentfound && $row['category_id'] == $currentid) || $row['parent_id'] == $currentid)
{
$rowdata = array();
foreach($row as $k => $v)
$rowdata[$k] = $v;
$cats[] = $rowdata;
if($row['parent_id'] == $currentid)
$cats = array_merge($cats, CategoryParentController::fetch_recursive($src_arr, $row['category_id'], true));
}
}
return $cats;
}
But I'm getting an error from PHP :
Maximum function nesting level of 100 reached, aborting!
I'm ordering the db results by parent_id and then by id to help out with the issue but it still persists.
As a side note by table contains ~250 records.
Finally found a solution that fits my needs! Thanks for all the help everyone and also for the constructive criticism :)
Laravel 4 - Eloquent. Infinite children into usable array?
Solution:
<?php
class ItemsHelper {
private $items;
public function __construct($items) {
$this->items = $items;
}
public function htmlList() {
return $this->htmlFromArray($this->itemArray());
}
private function itemArray() {
$result = array();
foreach($this->items as $item) {
if ($item->parent_id == 0) {
$result[$item->name] = $this->itemWithChildren($item);
}
}
return $result;
}
private function childrenOf($item) {
$result = array();
foreach($this->items as $i) {
if ($i->parent_id == $item->id) {
$result[] = $i;
}
}
return $result;
}
private function itemWithChildren($item) {
$result = array();
$children = $this->childrenOf($item);
foreach ($children as $child) {
$result[$child->name] = $this->itemWithChildren($child);
}
return $result;
}
private function htmlFromArray($array) {
$html = '';
foreach($array as $k=>$v) {
$html .= "<ul>";
$html .= "<li>".$k."</li>";
if(count($v) > 0) {
$html .= $this->htmlFromArray($v);
}
$html .= "</ul>";
}
return $html;
}
}

Code help, Unlimited php menu

Just got this code working for 2 levels of my menu. But I want it to work with unlimited levels.
Do any of you guys have an idea where to start?
Right now if I type in more levels in the database it says "Undefined index Linnk & Label Line 29", and the new parent that has been entered does not show up.
$sql = "SELECT id, label, link_url, parent_id FROM dyn_menu ORDER BY parent_id, id ASC";
$items = mysql_query($sql);
while ($obj = mysql_fetch_object($items)) {
if ($obj->parent_id == 0) {
$parent_menu[$obj->id]['label'] = $obj->label;
$parent_menu[$obj->id]['link'] = $obj->link_url;
} else {
$sub_menu[$obj->id]['parent'] = $obj->parent_id;
$sub_menu[$obj->id]['label'] = $obj->label;
$sub_menu[$obj->id]['link'] = $obj->link_url;
if (!isset($parent_menu[$obj->parent_id]['count'])) {
$parent_menu[$obj->parent_id]['count'] = 0;
}
$parent_menu[$obj->parent_id]['count']++;
}
}
mysql_free_result($items);
function dyn_menu($parent_array, $sub_array, $qs_val = "menu", $main_id = "nav", $sub_id = "subnav", $extra_style = "foldout") {
$menu = "<ul id=\"".$main_id."\">\n";
foreach ($parent_array as $pkey => $pval) {
if (!empty($pval['count'])) {
$menu .= " <li><a class=\"".$extra_style."\" href=\"".$pval['link']."?".$qs_val."=".$pkey."\">".$pval['label']."</a></li>\n";
} else {
$menu .= " <li>".$pval['label']."</li>\n";
}
if (!empty($_REQUEST[$qs_val])) {
$menu .= "<ul id=\"".$sub_id."\">\n";
foreach ($sub_array as $sval) {
if ($pkey == $_REQUEST[$qs_val] && $pkey == $sval['parent']) {
$menu .= "<li>".$sval['label']."</li>\n";
}
}
$menu .= "</ul>\n";
}
}
$menu .= "</ul>\n";
return $menu;
}
function rebuild_link($link, $parent_var, $parent_val) {
$link_parts = explode("?", $link);
$base_var = "?".$parent_var."=".$parent_val;
if (!empty($link_parts[1])) {
$link_parts[1] = str_replace("&", "##", $link_parts[1]);
$parts = explode("##", $link_parts[1]);
$newParts = array();
foreach ($parts as $val) {
$val_parts = explode("=", $val);
if ($val_parts[0] != $parent_var) {
array_push($newParts, $val);
}
}
if (count($newParts) != 0) {
$qs = "&".implode("&", $newParts);
}
return $link_parts[0].$base_var.$qs;
} else {
return $link_parts[0].$base_var;
}
}
echo dyn_menu($parent_menu, $sub_menu, "menu", "nav", "subnav");
In order to do this, you'll want to use a recursive function to handle your array -> list transformation.
Here's an example:
<?php
function arrToUl($arr) {
$out = '<ul>';
foreach($arr as $key=>$val) {
$out .= '<li>';
$out .= is_array($val) ? arrToUl($val) : $val;
$out .= '</li>';
}
return $out . '</ul>';
}
$arr = array('firstval','secondval',array('firstval2','secondval2',array('firstval3','secondval3',array('firstval4','secondval4',array('firstval5','secondval5')))));
echo arrToUl($arr);
Output in a jsfiddle.

Categories