I am trying to Insert my Categories SQL tables with a JSON in the below format.
[
{"id":21, "children": [{"id":4},{"id":7}]},
{"id":6},
{"id":5},
{"id":20},
{"id":10},
{"id":9}
]
I have tried to make it possible with this Code:
if(isset($_POST['category'])){
if(in_array($_GET['key'], $_SESSION['key'])){
unset($_SESSION['key'][array_search($_GET['key'], $_SESSION['key'])]);
$i = 1;
$rootof = array();
foreach($_POST['category'] as $cat => $parent){
if($parent == 'children'){
$p = "NULL";
$root = "NULL";
}else{
$p = intval($parent);
if(isset($rootof[$p])){
$root = $rootof[$p];
$rootof[intval($cat)] = $rootof[$p];
}else{
$root = $p;
$rootof[intval($cat)] = $p;
}
}
mysqli_query($db, "UPDATE ads_categories SET category_order = $i, category_parent = $p, category_root = $root WHERE category_id = ".intval($cat));
$i++;
}
echo 'Success';
}else{
echo 'Error';
}
}
I expect Saving the Categories by Id and subcategories (children) to Database.
I want to Insert Id 21, 6, 5 to categories->id,
if array has Children it means that it has subcategories.
subcategories has category_parent id to main category
Example: Categorie ID 4 category_parent would be 21
Related
I am playing around with the below code, I am making my personal "music database". In my mysql I have the following tables:
Music Categories
Music Artists
Music Tracks
The code below works fine except it doesn't display the first track of the database, it skips it, but it displays all the rest just fine. If I take the below example, the data displayed is as follows:
Category: 70's
artist2 trackname2
Category: 90's
artist3 trackname3
So, the first track get's skipped. I have been playing around with the code, but I cannot get it to work. It should be displayed like this:
Category: 70's
artist1 trackname1
artist2 trackname2
Category: 90's
artist3 trackname3
Example of how it looks like in the database:
music_categories:
musicID name
1 70s
2 80s
3 90s
music_artists:
artistID name
1 artist1
2 artist2
3 artist3
music_tracks:
id musicID artistID track
1 1 1 trackname1
2 1 2 trackname2
3 3 1 trackname3
Each music track has one artist and one category. I am using the code below in my classes.php file:
public function grabResults($table)
{
$result = 'SELECT * FROM '.$table;
$query = $this->mysqli->query($result);
if($query)
{
while($row = $query->fetch_assoc())
{
$rows[] = $row;
}
return $rows;
}
else {
return false;
}
}
And this is the code itself:
$categories = $data->grabResults(music_categories);
$artists = $data->grabResults(music_artists);
$tracks = $data->grabResults(music_tracks);
$catName = '';
$counter = 0;
foreach ($categories as $category)
{
foreach ($tracks as $track)
{
if($category['name'] != $catName)
{
$countID = $category['id'];
$total = $data->mysqli->query("SELECT `musicID` FROM `music_tracks` WHERE `musicID` = '$countID' ");
$totalCount = $total->num_rows;
if($totalCount > 0)
{
echo $category['name'];
}
$catName = $category['name'];
$counter = 0;
}
if($counter > 0)
{
if($category['id'] == $track['mid'])
{
foreach ($artists as $artist)
{
if($track['artistID'] == $artist['id'])
{
echo $artist['name'];
}
}
echo $track['track'];
echo "<br>";
}
}
$counter++;
}
}
i'm trying to build a feed generator based on this post Magento: Product data extraction for product feed. for the time beeing my problem is with the categories and subcategories of the product.
my code:
<?php
error_reporting(E_ALL | E_STRICT);
ini_set("display_errors", 1);
define('SAVE_FEED_LOCATION','feed/compari.csv');
//$objDateTime = new DateTime('NOW');
require 'app/Mage.php';
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
$products = Mage::getModel('catalog/product')->getCollection();
$products->addAttributeToFilter('status', 1); //1 is set to select product in stock
$products->addAttributeToFilter('visibility', 4); //4 is set to select active products
$products->addAttributeToSelect('*');
$prodIds=$products->getAllIds();
$product = Mage::getModel('catalog/product');
$counter = 0;
$feedaray=[];
foreach($prodIds as $productId) {
if (++$counter < 500000){
$product->load($productId);
$title_temp = $product->getName();
if (strlen($title_temp) > 255){
$title_temp = str_replace("Supply", "", $title_temp);
$title_temp = str_replace(" ", " ", $title_temp);
} //$title_temp will hold the product name
$maincat = $subcats = '';
$categoryCollection = $product->getCategoryCollection();
if i do a var_dump($title_temp.' categorie: '.$categorie_id);
foreach($categoryCollection as $cat){
$categorie_id=$cat->getData()['entity_id'];
$_cat_ac = Mage::getModel('catalog/category')->load($categorie_id);
if($subcats_ac == ''){
$maincat_ac = $subcats_ac = $_cat_ac->getName();
}else {
$subcats_ac .= ">".$_cat_ac->getName();
}
echo '<pre>';
var_dump($title_temp.' categorie: '.$categorie_id);
echo '</pre>';
}
i'm geting the corect result:
string(59) "product 1 categorie: 3" - prime category
string(60) "product 1 categorie: 37" - sub category
string(45) "product 2 categorie: 4" - prime category
string(46) "product 2 categorie: 21" - sub category
further i need to prepare the data for exporting to csv, and i do it like this:
$stock = Mage::getModel('cataloginventory/stock_item')->loadByProduct($productId);
$product_data = array();
$product_data['ProductID'] = $productId;
$product_data['ProductName'] = substr(iconv("UTF-8","UTF-8//IGNORE",$title_temp), 0, 255);
$product_data['SKUnumber'] = $product->getSku();
$product_data['PrimaryCategory'] = $maincat_ac; //this is spitting same data for all products
$product_data['SecondaryCategory'] = $subcats_ac; //this is spitting same data for all products
$product_data['ProductURL'] = $StoreURL.$product->getUrlPath(); //$StroeURL is set as a string
$product_data['ProductImageURL'] = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA).'catalog/product'.$product->getImage();
$product_data['ShortProductDescription'] = substr(iconv("UTF-8","UTF-8//IGNORE",$product->getDescription()), 0, 80)."...";
$product_data['LongProductDescription'] = substr(iconv("UTF-8","UTF-8//IGNORE",$product->getDescription()), 0, 2000);
$product_data['SalePrice'] = round($product->getFinalPrice(),2);
$product_data['RetailPrice'] = round($product->getPrice(),2);
$product_data['ManufacturerName'] =$product->getAttributeText('manufacturer');
$product_data['Quantity'] = round($stock->getQty(),2);
$product_data['Currency'] = Mage::app()->getStore()->getCurrentCurrencyCode();
foreach($product_data as $k=>$val){
$bad=array('"',"\r\n","\n","\r","\t");
$good=array(""," "," "," ","");
$product_data[$k] = str_replace($bad,$good,$val);
}
$feedaray[]=$product_data;
echo $counter . " ";
}
}
$handle=fopen(SAVE_FEED_LOCATION, 'w');
foreach ($feedaray as $fields) {
fputcsv($handle, $fields);
}
fclose($handle);
?>
the problem is with the maincat_ac and subcat_ac that are not displaing corect data.
solution for the problem
$cats=[];
foreach($categoryCollection as $cat){
$cats[]=$cat->getData()['entity_id'];
}
foreach ($cats as $category_id) {
$_cat = Mage::getModel('catalog/category')->load($category_id) ;
if($subcats == ''){
$maincat = $subcats = $_cat->getName();
}else {
$subcats .= ">".$_cat->getName();
}
}
may be it isn't the best solution. if you have another idea please share.
regards
I have in my table records that are related one to another by a parentId field. When fetching them from the DB I need to create JSON array of objects where the child records are added to 'children' property of parent objects :
[{
//main object
children : [
{
//#1st level children object
children: [
{
//#2nd level children object
}
]
}
]
},
{
(...)
]
But if there are no records with parentId equal to current record, then this property shouldn't be added to the object.
Right now I'm building the JSON string manually :
//first get the parents
$q = 'SELECT * FROM table WHERE parentId = 0';
$r = mysql_query($q);
$x=1;
$nr = mysql_num_rows($r);
while($e = mysql_fetch_array($r)){
if($x==1){
echo '[ { ';
}
else{
echo ' { ';
}
if($e['leaf']==1){
$leaf = 'true';
} else {
$leaf = 'false';
}
echo '"EndDate" : "'.str_replace('T00:00:00','',$e['EndDate']).'",
"Id" : '.$e['Id'].',
"Name" : "'.$e['Name'].'",
"BaselineStartDate" : "'.str_replace('T00:00:00','',$e['BaselineStartDate']).'"';
if($leaf){
echo ',"leaf": '.$leaf.'';
}
childs($e['Id'], $x, $nr);
if($x<$nr){
echo ',';
}
$x++;
}
if($x>1){
echo ']';
}
function childs($id, $x, $nr, $x2='', $nr2=''){
//now see if there are childern
$q2 = 'SELECT * FROM table WHERE parentId = "'.$id.'" ';
$r2 = mysql_query($q2);
$nr2 = mysql_num_rows($r2);
if($nr2>0){
echo ',"children": [ ';
$x2 =1;
while($e2 = mysql_fetch_array($r2)){
if($e2['leaf']==1){
$leaf2 = 'true';
}
else{
$leaf2 = 'false';
}
echo '{
"EndDate" : "'.str_replace('T00:00:00','',$e2['EndDate']).'",
"Id" : '.$e2['Id'].',
"Name" : "'.$e2['Name'].'",
"BaselineStartDate" : "'.str_replace('T00:00:00','',$e2['BaselineStartDate']).'",
"leaf" : "'.$leaf2.'"';
childs($e2['Id'],$x,$nr,'',$x2,$nr2);
if($x2<$nr2){
echo ',';
}
$x2++;
}
echo '] }';
}
else{
echo ',"children" : []}';
}
}
Is there an easy way to make this code more robust using some built-in PHP features like fetch_assoc or something like that?
You should rather..
Fetch the results from the database
Reformat as per the requirement (related code you can use with some alteration PHP Create a Multidimensional Array from an array with relational data
Then finally, json_encode the resulting array
I want to extend Nodes with the title of the parentnode so I can display a hierarchy link.
I have a solution that sometimes works:
function modulename_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL)
{
switch ($op)
{
case 'view':
loadParentTitle($node);
break;
}
}
function loadParentTitle(&$node)
{
$title = $node->title;
$query = "SELECT mlid, p1, p2,p4,p5,p6,p7,p8,p9 FROM menu_links WHERE link_title like '%%%s%%'";
$data = db_fetch_array(db_query($query, $title));
$mlid = $data["mlid"];
$i = 9;
while (($data["p". $i] == 0 || $data["p". $i] == $mlid) && $i >= 0)
{
$i--;
}
if ($i > 0)
{
$query = "SELECT `link_title` as parentTitle from `menu_links` WHERE mlid = " . $data["p" . $i];
$data = db_fetch_array(db_query($query));
$parentTitle = ($data["parentTitle"]);
}
else
{
$parentTitle = $title;
}
$node->content['#parentTitle'] = $parentTitle;
}
This works as long as the title of the item is the same as the Menu Title. However i'm looking for a solution that will work all the time. Any ideas?
You did not specify really what do you mean by 'parent node' but the mlid of the parent of a menu link is stored in menu_links.plid. Now, the link_path is going to be node/nid and you can fetch the title from there.
$mlid = db_result(db_query("SELECT plid FROM {menu_links} WHERE link_path = 'node/%d'", $node->nid));
$link_path = db_result(db_query("SELECT link_path FROM {menu_links} WHERE mlid = %d", $mlid));
$title = db_result(db_query("SELECT title FROM {node} WHERE nid = %d", substr($link_path, 5));
The first two queries can be unified by a JOIN but I strongly recommend against getting the third in there too (you can with CONCAT('node/', nid) = parent.link_path) because that is not going to be indexable. These three queries should be practically instant.
P.S. You won't forget to check_plain($title) before printing, would you? :)
function build_list($id=0,$collapsed="") //return an array with the categories ordered by position
{
$RootPos = "";
$this->c_list = array();
if($id != 0){
$this_category = $this->fetch($id);
$positions = explode(">",$this_category['position']);
$RootPos = $positions[0];
}
// lets fetch the root categories
$sql = "SELECT *
FROM ".$this->table_name."
WHERE position RLIKE '^([0-9]+>){1,1}$' AND c_group = '".$this->Group."'
ORDER BY c_name";
$res = mysql_query($sql) or die(trigger_error("<br><storng><u>MySQL Error:</u></strong><br>".mysql_error()."<br><br><storng><u>Query Used:</u></strong><br>".$sql."<br><br><storng><u>Info:</u></strong><br>",E_USER_ERROR));
while($root = mysql_fetch_array($res)){
$root["prefix"] = $this->get_prefix($root['position']);
$this->c_list[$root['id']] = $root;
if($RootPos == $root['id'] AND $id != 0 AND $collapsed != ""){
$this->list_by_id($id);
continue;
}else{
// lets check if there is sub-categories
if($collapsed == "" AND $id==0){
$has_children = $this->has_children($root['position']);
if($has_children == TRUE) $this->get_children($root['position'],0);
}}}
return $this->c_list;
}
// He is the Author of the code...
Categories Class
Author: Shadi Ali
Now I want to just return the Categories and Sub Categories from the above code.
function browse() {
$categories = new categories;
$categories_list = $categories->build_list();
foreach($categories_list as $c)
{
return $c->$id;
}
}
The above code is not working.... can anyone help me out.
Here are two problems with the browse() function:
The return statement is inside the foreach loop. The statement will return one value for one of the items in the $categories-list (at most), and not continue to loop over the rest of the $categories-list.
The $id variable is never declared or initialised in return $c->$id, perhaps you meant to use $c['id'] or $c->id