With PHP, I need to create a three-level-deep navbar. I have data like this:
And I need it to be organized like so:
Napkins
--Colored Napkins
----American Tradition
--White Beverage Napkins
----American Digital
----American Tradition
----American Hi-Speed
--White Luncheon Napkins
----American Digital
----American Tradition
----American Hi-Speed
--White Dinner Napkins
...(etc)...
Plates
--Eco-Plates
----American Tradition
--Plastic Trays
...(etc)...
Just using a relatively simple <ul> structure with <li> and <a>. Clearly a loop is needed to go through the rows of data. And I know that I'd need to do lots of "testing" to see if the "current" category/subcategory/method matches the one from the previous iteration of the loop.
But I'm having trouble getting the <ul> and <li> tags to close at the correct locations and to not show the print method tier when there is only one print method for a given category/subcategory. Or when there is no print method (sometimes it can be null, such as for plastic utensils). How can I set this up?
Edit
The code I have so far, which almost works, but is very clunky ($items is the data from the database):
function addMethodMenuItem($result, $short_cat_name, $short_subcat_name, $short_method_name, $this_method_name)
{
$result .= "<li>";
$result .= "<a";
$result .= " href=\"product.php?category={$short_cat_name}&subcategory={$short_subcat_name}&printMethod={$short_method_name}\"";
$result .= " target=\"_self\"";
$result .= " title=\"{$this_method_name}\">";
$result .= $this_method_name;
$result .= "</a>";
$result .= "</li>";
return $result;
}
function addSubMenuItem($item, $previous_cat_name, $previous_subcat_name, $result, $newCat)
{
$this_cat_name = $item["category_name"];
$this_subcat_name = $item["subcategory_name"];
$this_method_name = $item["method_name"];
$short_cat_name = $item["category_short"];
$short_subcat_name = $item["subcategory_short"];
$short_method_name = $item["method_short"];
if ($this_subcat_name != $previous_subcat_name || $this_cat_name != $previous_cat_name) { // We have to create a new "subcategory" menu item
if ($previous_subcat_name != null && !$newCat) { // if this isn't the first subcategory menu item of the category.
$result .= "</ul></li>";
}
$result .= "<li>";
$result .= "<a class=\"ajxsub\"";
$result .= " href=\"#\">";
$result .= $this_subcat_name;
$result .= "</a>";
$result .= "<ul>";
}
$result = addMethodMenuItem($result, $short_cat_name, $short_subcat_name, $short_method_name, $this_method_name);
return $result;
}
function printMenu(array $items, $previous_cat_name, $result)
{
// $result .= "<ul>";
$previous_subcat_name = null;
foreach ($items as $item) {
$newCat = false;
$this_cat_name = $item["category_name"];
$this_subcat_name = $item["subcategory_name"];
if ($this_cat_name != $previous_cat_name) {
if ($previous_cat_name != null) { // if this isn't the very first top-level menu item.
$result .= "</ul></li>";
$result .= "</ul></li>";
$newCat = true;
}
$result .= "<li>";
$result .= "<a class=\"ajxsub\"";
$result .= " href=\"#\">";
$result .= $this_cat_name;
$result .= "</a>";
$result .= "<ul>";
}
$result = addSubMenuItem($item, $previous_cat_name, $previous_subcat_name, $result, $newCat);
$previous_subcat_name = $this_subcat_name;
$previous_cat_name = $this_cat_name;
}
$result .= "</ul></li>";
// $result .= "</ul>";
return $result;
}
Give this a whirl - assumes you have the data already sorted (else sort it first):
$flds = ['category_name', 'subcategory_name', 'method_name'];
$lval = ['it will never be this'];
$result = "";
$start = true;
foreach ($items as $item) {
if ($start) {
$result .= "<ul>";
$first = $start = false;
} else $first = true;
foreach ($flds as $k=>$val) {
if ($item[$val] != $lval[$k]) {
$result .= genhtml($k, $item[$val], $first);
$first = false;
$lval[$k] = $item[$val];
$lval[$k+1] = ''; // Don't care if this goes over the max
}
}
}
if (!$start) $result .= "</ul></li></ul></li></ul>\n";
echo $result;
function genhtml($level, $value, $first) {
switch ($level) {
case 0:
$close = $first ? "</ul></li></ul></li>" : "";
return "{$close}<li>{$value}<ul>\n";
case 1:
$close = $first ? "</ul></li>" : "";
return " {$close}<li>{$value}<ul>\n";
case 2:
return " <li>{$value}</li>\n";
default:
throw new Exception("I don't know how to do '{$level}'");
}
}
The code above (with some of your data) produces:
<ul><li>Napkins<ul>
<li>Colored Napkins<ul>
<li>American Tradition</li>
</ul></li><li>White Beverage Napkins<ul>
<li>American Digital</li>
<li>American Tradition</li>
<li>American Hi Speed</li>
</ul></li><li>White Luncheon Napkins<ul>
<li>American Digital</li>
<li>American Tradition</li>
<li>American Hi Speed</li>
</ul></li><li>White Dinner Napkins<ul>
<li>American Digital</li>
<li>American Tradition</li>
<li>American Hi Speed</li>
</ul></li></ul></li><li>Plates<ul>
<li>Eco Plates<ul>
<li>American Tradition</li>
</ul></li></ul></li></ul>
(Not pretty, but I think its right).
Also will ignore duplicate records (maybe not what you want?). If you need other data from your record to produce the html, pass $item to genhtml as well.
Related
I need two print the same rows which retrieved from the db, in two different locations in same php file.
I know it is better to have a function. It tried, It doesn't work properly.
I am using the below code print the said rows/
$get_g = "SELECT * FROM profile_groups";
$get_gr = mysqli_query($condb ,$get_g);
if(mysqli_num_rows($get_gr) > 0)
{
while($groups = mysqli_fetch_array($get_gr))
{
echo "<option value='".$groups['profile_gid']."'>".$groups['profile_gname']."</option>";
}
}
else
{
echo '<option value="">Empty - No Groups!!</option>';
}
I need to print exactly the same code twice in two different location in a php file.
I think it is not a good idea to retrieve data twice from the server by pasting the above code twice.
Is there any way to recall or reprint the retrieved data in second place which I need to print.
Edit : Or else, if someone can help me to convert this to a function?
I converted this into a function. It prints only first row.
Edit 2 : Following is my function
unction getGroup($dbconn)
{
$get_g = "SELECT * FROM profile_groups";
$get_gr = mysqli_query($dbconn ,$get_g);
if(mysqli_num_rows($get_gr) > 0)
{
while($groups = mysqli_fetch_array($get_gr))
{
$groupData = "<option value='".$groups['profile_gid']."'>".$groups['profile_gname']."</option>";
}
}
else
{
echo '<option value="">Empty - No Groups!!</option>';
}
return $groupData;
You can store the records coming from the DB in array and use a custom function to render the element
$get_g = "SELECT * FROM profile_groups";
$get_gr = mysqli_query($condb ,$get_g);
$options = []; //store in an array
if(mysqli_num_rows($get_gr) > 0)
{
while($groups = mysqli_fetch_array($get_gr))
{
$options[$groups['profile_gid']] = $groups['profile_gname'];
}
}
Now you can use the $options array many times in your page
echo renderElement($options);
function renderElement($ops){
$html = '';
foreach($ops as $k => $v){
$html .= "<option value={$k}>{$v}</option>";
}
return $html;
}
If the data is same for both places, put the entire string into variable, then echo it on those two places.
instead of
echo "here\n";
echo "there\n";
do
$output = "here\n";
$output .= "there\n";
then somewhere
echo $output
on two places....
Values are being stored in groups array, hence you can use a foreach loop elsewhere to get values from the array:
$groups = array();
$get_g = "SELECT * FROM profile_groups";
$get_gr = mysqli_query($condb ,$get_g);
if(mysqli_num_rows($get_gr) > 0)
{
while($groups = mysqli_fetch_array($get_gr))
{
echo "<option value='".$groups['profile_gid']."'>".$groups['profile_gname']."</option>";
}
}
else
{
echo '<option value="">Empty - No Groups!!</option>';
}
// use here
foreach($groups as $group)
{
echo $group['profile_gid'] . " ". $group['profile_gname'] . "<br/>";
}
class ProfileGroups
{
public $profile_groups_options;
public static function get_profile_groups_options($condb) {
$get_g = "SELECT * FROM profile_groups";
if( isset( $this->profile_groups_options ) && $this->profile_groups_options != '') {
return $this->profile_groups_options;
}
$get_gr = mysqli_query($condb ,$get_g);
if(mysqli_num_rows($get_gr) > 0)
{
while($groups = mysqli_fetch_array($get_gr))
{
$this->profile_groups_options .= "<option value='".$groups['profile_gid']."'>".$groups['profile_gname']."</option>";
}
}
else
{
$this->profile_groups_options .= '<option value="">Empty - No Groups!!</option>';
}
return $this->profile_groups_options;
}
}
ProfileGroups::get_profile_groups_options($condb);
I have a database with lots of courses in for example, breakfast_cereal, breakfast_toast, lunch_salad, lunch_main etc etc
Im using this to put the data they enter into a variable containing there results, for example:
breakfast_toast = Wholemeal;Brown;50/50;
and
breakfast_hotdrinks = Tea;Coffee;Milk;
This is the script im using to gather that information:
if(!empty($_POST['toast_selection'])) {
foreach($_POST['toast_selection'] as $toast) {
$toast = trim($toast);
if(!empty($toast)) {
$toastchoices .= "$toast;";
}
}
}
This works absolutely fine, But i have about a lot of entries to collect and if they add more to the database i want them to automatically gather.
I had a go at trying to think of a way but i just can't figure it out, This is what i tried:
All the inputs are called the same as the $course_menuname, for example breakfast_cereal[]
$query = "SELECT * FROM course";
$result = mysql_query($query);
while($row = mysql_fetch_array($result))
{
$course_menuname = $row['course_menuname']; #E.G breakfast_cereal, breakfast_toast, lunch_main
$course_item = $row['course_jsname']; #E.G cereal, toast, jacketpotato
$postResults = $_POST[''.$course_menuname .''];
if(!empty($postResults)) {
echo $postResults."<br />";
foreach($postResults as $course_item) {
$course_item = trim($course_item);
if(!empty($course_item)) {
$course_item1 .= "$course_item;";
}
}
}
echo $course_item1."<br />";
}
This is what the end result should look for
if(!empty($_POST['toast'])) {
foreach($_POST['toast'] as $toast) {
$toast = trim($toast);
if(!empty($toast)) {
$toastchoices .= "$toast;";
}
}
}
if(!empty($_POST['toastextra_selection'])) {
#Gather Toast EXTRAs Choices
foreach($_POST['toastextra_selection'] as $toastextra) {
$toastextra = trim($toastextra);
if(!empty($toastextra)) {
$toastextrachoices .= "$toastextra;";
}
}
}
if(!empty($_POST['toastextra_selection'])) {
#Gather Cold Drinks Choices
foreach($_POST['colddrinks_selection'] as $colddrinks) {
$colddrinks = trim($colddrinks);
if(!empty($colddrinks)) {
$colddrinkschoices .= "$colddrinks;";
}
}
}
if(!empty($_POST['hotdrinks_selection'])) {
#Gather Hot Drinks Choices
foreach($_POST['hotdrinks_selection'] as $hotdrinks) {
$hotdrinks = trim($hotdrinks);
if(!empty($hotdrinks)) {
$hotdrinkschoices .= "$hotdrinks;";
}
}
}
First of all you should not use the mysql_* functions anymore. These functions are marked as deprecated. Alternativly you can use PDO or the mysqli_* functions.
I guess group change is what you need. Let 's start with a simple example.
try {
$data = array();
$pdo = new PDO(...);
foreach ($pdo->query("SELECT * FROM course") as $row) {
if (!isset($data[$row['course_menuname'])) {
$data[$row['course_menuname']] = array();
}
if (!empty($row['course_item'] && in_array($row['course_item'], $_POST[$row['course_menuname'])) {
$data[$row['course_menuname'][] = $row['course_item'];
}
}
} catch (PDOException $e) {
// error handling
}
// Output all choices by menuname
foreach ($data as $key => $value) {
echo "Choices for " . $key . "\n";
echo implode(";", $value) . "\n";
}
I'm really stumped on how Twitter expects users of its API to convert the plaintext tweets it sends to properly linked HTML.
Here's the deal: Twitter's JSON API sends this set of information back when you request the detailed data for a tweet:
{
"created_at":"Wed Jul 18 01:03:31 +0000 2012",
"id":225395341250412544,
"id_str":"225395341250412544",
"text":"This is a test tweet. #boring #nbc http://t.co/LUfDreY6 #skronk #crux http://t.co/VpuMlaDs #twitter",
"source":"web",
"truncated":false,
"in_reply_to_status_id":null,
"in_reply_to_status_id_str":null,
"in_reply_to_user_id":null,
"in_reply_to_user_id_str":null,
"in_reply_to_screen_name":null,
"user": <REDACTED>,
"geo":null,
"coordinates":null,
"place":null,
"contributors":null,
"retweet_count":0,
"entities":{
"hashtags":[
{
"text":"boring",
"indices":[22,29]
},
{
"text":"skronk",
"indices":[56,63]
}
],
"urls":[
{
"url":"http://t.co/LUfDreY6",
"expanded_url":"http://www.twitter.com",
"display_url":"twitter.com",
"indices":[35,55]
},
{
"url":"http://t.co/VpuMlaDs",
"expanded_url":"http://www.example.com",
"display_url":"example.com",
"indices":[70,90]
}
],
"user_mentions":[
{
"screen_name":"nbc",
"name":"NBC",
"id":26585095,
"id_str":"26585095",
"indices":[30,34]
},
{
"screen_name":"crux",
"name":"Z. D. Smith",
"id":407213,
"id_str":"407213",
"indices":[64,69]
},
{
"screen_name":"twitter",
"name":"Twitter",
"id":783214,
"id_str":"783214",
"indices":[91,99]
}
]
},
"favorited":false,
"retweeted":false,
"possibly_sensitive":false
}
The interesting parts, for this question, are the text element and the entries in the hashtags, user_mentions, and urls arrays. Twitter is telling us where in the text element the hastags, mentions, and urls appear with the indices arrays... so here's the crux of the question:
How do you use those indices arrays?
You can't just use them straight up by looping over each link element with something like substr_replace, since replacing the first link element in the text will invalidate all the index values for subsequent link elements. You also can't use substr_replace's array functionality, since it only works when you give it an array of strings for the first arg, rather than a single string (I've tested this. The results are... strange).
Is there some function that can simultaneously replace multiple index-delimited substrings in a single string with different replacement strings?
All you have to do to use the indices twitter provides straight up with a simple replace is collect the replacements you want to make and then sort them backwards. You can probably find a more clever way to build $entities, I wanted them optional anyway, so I KISS as far as that went.
Either way, my point here was just to show that you don't need to explode the string and character count and whatnot. Regardless of how you do it, all you need to to is start at the end and work to the beginning of the string, and the index twitter has is still valid.
<?php
function json_tweet_text_to_HTML($tweet, $links=true, $users=true, $hashtags=true)
{
$return = $tweet->text;
$entities = array();
if($links && is_array($tweet->entities->urls))
{
foreach($tweet->entities->urls as $e)
{
$temp["start"] = $e->indices[0];
$temp["end"] = $e->indices[1];
$temp["replacement"] = "<a href='".$e->expanded_url."' target='_blank'>".$e->display_url."</a>";
$entities[] = $temp;
}
}
if($users && is_array($tweet->entities->user_mentions))
{
foreach($tweet->entities->user_mentions as $e)
{
$temp["start"] = $e->indices[0];
$temp["end"] = $e->indices[1];
$temp["replacement"] = "<a href='https://twitter.com/".$e->screen_name."' target='_blank'>#".$e->screen_name."</a>";
$entities[] = $temp;
}
}
if($hashtags && is_array($tweet->entities->hashtags))
{
foreach($tweet->entities->hashtags as $e)
{
$temp["start"] = $e->indices[0];
$temp["end"] = $e->indices[1];
$temp["replacement"] = "<a href='https://twitter.com/hashtag/".$e->text."?src=hash' target='_blank'>#".$e->text."</a>";
$entities[] = $temp;
}
}
usort($entities, function($a,$b){return($b["start"]-$a["start"]);});
foreach($entities as $item)
{
$return = substr_replace($return, $item["replacement"], $item["start"], $item["end"] - $item["start"]);
}
return($return);
}
?>
Ok so I needed to do exactly this and I solved it. Here is the function I wrote. https://gist.github.com/3337428
function parse_message( &$tweet ) {
if ( !empty($tweet['entities']) ) {
$replace_index = array();
$append = array();
$text = $tweet['text'];
foreach ($tweet['entities'] as $area => $items) {
$prefix = false;
$display = false;
switch ( $area ) {
case 'hashtags':
$find = 'text';
$prefix = '#';
$url = 'https://twitter.com/search/?src=hash&q=%23';
break;
case 'user_mentions':
$find = 'screen_name';
$prefix = '#';
$url = 'https://twitter.com/';
break;
case 'media':
$display = 'media_url_https';
$href = 'media_url_https';
$size = 'small';
break;
case 'urls':
$find = 'url';
$display = 'display_url';
$url = "expanded_url";
break;
default: break;
}
foreach ($items as $item) {
if ( $area == 'media' ) {
// We can display images at the end of the tweet but sizing needs to added all the way to the top.
// $append[$item->$display] = "<img src=\"{$item->$href}:$size\" />";
}else{
$msg = $display ? $prefix.$item->$display : $prefix.$item->$find;
$replace = $prefix.$item->$find;
$href = isset($item->$url) ? $item->$url : $url;
if (!(strpos($href, 'http') === 0)) $href = "http://".$href;
if ( $prefix ) $href .= $item->$find;
$with = "$msg";
$replace_index[$replace] = $with;
}
}
}
foreach ($replace_index as $replace => $with) $tweet['text'] = str_replace($replace,$with,$tweet['text']);
foreach ($append as $add) $tweet['text'] .= $add;
}
}
It's an edge case but the use of str_replace() in Styledev's answer could cause issues if one entity is contained within another. For example, "I'm a genius! #me #mensa" could become "I'm a genius! #me #mensa" if the shorter entity is substituted first.
This solution avoids that problem:
<?php
/**
* Hyperlinks hashtags, twitter names, and urls within the text of a tweet
*
* #param object $apiResponseTweetObject A json_decoded() one of these: https://dev.twitter.com/docs/platform-objects/tweets
* #return string The tweet's text with hyperlinks added
*/
function linkEntitiesWithinText($apiResponseTweetObject) {
// Convert tweet text to array of one-character strings
// $characters = str_split($apiResponseTweetObject->text);
$characters = preg_split('//u', $apiResponseTweetObject->text, null, PREG_SPLIT_NO_EMPTY);
// Insert starting and closing link tags at indices...
// ... for #user_mentions
foreach ($apiResponseTweetObject->entities->user_mentions as $entity) {
$link = "https://twitter.com/" . $entity->screen_name;
$characters[$entity->indices[0]] = "<a href=\"$link\">" . $characters[$entity->indices[0]];
$characters[$entity->indices[1] - 1] .= "</a>";
}
// ... for #hashtags
foreach ($apiResponseTweetObject->entities->hashtags as $entity) {
$link = "https://twitter.com/search?q=%23" . $entity->text;
$characters[$entity->indices[0]] = "<a href=\"$link\">" . $characters[$entity->indices[0]];
$characters[$entity->indices[1] - 1] .= "</a>";
}
// ... for http://urls
foreach ($apiResponseTweetObject->entities->urls as $entity) {
$link = $entity->expanded_url;
$characters[$entity->indices[0]] = "<a href=\"$link\">" . $characters[$entity->indices[0]];
$characters[$entity->indices[1] - 1] .= "</a>";
}
// ... for media
foreach ($apiResponseTweetObject->entities->media as $entity) {
$link = $entity->expanded_url;
$characters[$entity->indices[0]] = "<a href=\"$link\">" . $characters[$entity->indices[0]];
$characters[$entity->indices[1] - 1] .= "</a>";
}
// Convert array back to string
return implode('', $characters);
}
?>
Jeff's solution worked well with English text but it got broken when the tweet contained non-ASCII characters. This solution avoids that problem:
mb_internal_encoding("UTF-8");
// Return hyperlinked tweet text from json_decoded status object:
function MakeStatusLinks($status)
{$TextLength=mb_strlen($status['text']); // Number of UTF-8 characters in plain tweet.
for ($i=0;$i<$TextLength;$i++)
{$ch=mb_substr($status['text'],$i,1); if ($ch<>"\n") $ChAr[]=$ch; else $ChAr[]="\n<br/>"; // Keep new lines in HTML tweet.
}
if (isset($status['entities']['user_mentions']))
foreach ($status['entities']['user_mentions'] as $entity)
{$ChAr[$entity['indices'][0]] = "<a href='https://twitter.com/".$entity['screen_name']."'>".$ChAr[$entity['indices'][0]];
$ChAr[$entity['indices'][1]-1].="</a>";
}
if (isset($status['entities']['hashtags']))
foreach ($status['entities']['hashtags'] as $entity)
{$ChAr[$entity['indices'][0]] = "<a href='https://twitter.com/search?q=%23".$entity['text']."'>".$ChAr[$entity['indices'][0]];
$ChAr[$entity['indices'][1]-1] .= "</a>";
}
if (isset($status['entities']['urls']))
foreach ($status['entities']['urls'] as $entity)
{$ChAr[$entity['indices'][0]] = "<a href='".$entity['expanded_url']."'>".$entity['display_url']."</a>";
for ($i=$entity['indices'][0]+1;$i<$entity['indices'][1];$i++) $ChAr[$i]='';
}
if (isset($status['entities']['media']))
foreach ($status['entities']['media'] as $entity)
{$ChAr[$entity['indices'][0]] = "<a href='".$entity['expanded_url']."'>".$entity['display_url']."</a>";
for ($i=$entity['indices'][0]+1;$i<$entity['indices'][1];$i++) $ChAr[$i]='';
}
return implode('', $ChAr); // HTML tweet.
}
Here is an updated answer that works with Twitter's new Extended Mode. It combines the answer by #vita10gy and the comment by #Hugo (to make it utf8 compatible), with a few minor tweaks to work with the new api values.
function utf8_substr_replace($original, $replacement, $position, $length) {
$startString = mb_substr($original, 0, $position, "UTF-8");
$endString = mb_substr($original, $position + $length, mb_strlen($original), "UTF-8");
$out = $startString . $replacement . $endString;
return $out;
}
function json_tweet_text_to_HTML($tweet, $links=true, $users=true, $hashtags=true) {
// Media urls can show up on the end of the full_text tweet, but twitter doesn't index that url.
// The display_text_range indexes show the actual tweet text length.
// Cut the string off at the end to get rid of this unindexed url.
$return = mb_substr($tweet->full_text, $tweet->display_text_range[0],$tweet->display_text_range[1]);
$entities = array();
if($links && is_array($tweet->entities->urls))
{
foreach($tweet->entities->urls as $e)
{
$temp["start"] = $e->indices[0];
$temp["end"] = $e->indices[1];
$temp["replacement"] = " <a href='".$e->expanded_url."' target='_blank'>".$e->display_url."</a>";
$entities[] = $temp;
}
}
if($users && is_array($tweet->entities->user_mentions))
{
foreach($tweet->entities->user_mentions as $e)
{
$temp["start"] = $e->indices[0];
$temp["end"] = $e->indices[1];
$temp["replacement"] = " <a href='https://twitter.com/".$e->screen_name."' target='_blank'>#".$e->screen_name."</a>";
$entities[] = $temp;
}
}
if($hashtags && is_array($tweet->entities->hashtags))
{
foreach($tweet->entities->hashtags as $e)
{
$temp["start"] = $e->indices[0];
$temp["end"] = $e->indices[1];
$temp["replacement"] = " <a href='https://twitter.com/hashtag/".$e->text."?src=hash' target='_blank'>#".$e->text."</a>";
$entities[] = $temp;
}
}
usort($entities, function($a,$b){return($b["start"]-$a["start"]);});
foreach($entities as $item)
{
$return = utf8_substr_replace($return, $item["replacement"], $item["start"], $item["end"] - $item["start"]);
}
return($return);
}
Here is a JavaScript version (using jQuery) of vita10gy's solution
function tweetTextToHtml(tweet, links, users, hashtags) {
if (typeof(links)==='undefined') { links = true; }
if (typeof(users)==='undefined') { users = true; }
if (typeof(hashtags)==='undefined') { hashtags = true; }
var returnStr = tweet.text;
var entitiesArray = [];
if(links && tweet.entities.urls.length > 0) {
jQuery.each(tweet.entities.urls, function() {
var temp1 = {};
temp1.start = this.indices[0];
temp1.end = this.indices[1];
temp1.replacement = '' + this.display_url + '';
entitiesArray.push(temp1);
});
}
if(users && tweet.entities.user_mentions.length > 0) {
jQuery.each(tweet.entities.user_mentions, function() {
var temp2 = {};
temp2.start = this.indices[0];
temp2.end = this.indices[1];
temp2.replacement = '#' + this.screen_name + '';
entitiesArray.push(temp2);
});
}
if(hashtags && tweet.entities.hashtags.length > 0) {
jQuery.each(tweet.entities.hashtags, function() {
var temp3 = {};
temp3.start = this.indices[0];
temp3.end = this.indices[1];
temp3.replacement = '#' + this.text + '';
entitiesArray.push(temp3);
});
}
entitiesArray.sort(function(a, b) {return b.start - a.start;});
jQuery.each(entitiesArray, function() {
returnStr = substrReplace(returnStr, this.replacement, this.start, this.end - this.start);
});
return returnStr;
}
You can then use this function like so ...
for(var i in tweetsJsonObj) {
var tweet = tweetsJsonObj[i];
var htmlTweetText = tweetTextToHtml(tweet);
// Do something with the formatted tweet here ...
}
Regarding vita10gy's helpful json_tweet_text_to_HTML(), I found a tweet that it could not format correctly: 626125868247552000.
This tweet has a nonbreaking space in it. My solution was to replace the first line of the function with the following:
$return = str_replace("\xC2\xA0", ' ', $tweet->text);
Performing a str_replace() on is covered here.
Problem:
I am trying to delete all sublevels of a category by using a class. Currently I can only make it delete two sublevels, not three.
The database table:
CREATE TABLE betyg_category (
CID int(11) NOT NULL AUTO_INCREMENT,
Item varchar(100) NOT NULL,
Parent int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (CID)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
The PHP class:
<?php
class ItemTree
{
var $itemlist = array();
function ItemTree($query)
{
$result = mysql_query($query) or die ('Database Error (' . mysql_errno() . ') ' . mysql_error());
while ($row = mysql_fetch_assoc($result))
{
$this->itemlist[$row['CID']] = array(
'name' => $row['Name'],
'parent' => $row['Parent']
);
}
}
function get_tree($parent, $with_parent=0)
{
$item_tree = array();
if ($with_parent == 1 && $parent != 0)
{
$item_tree[$parent]['name'] = $this->itemlist[$parent]['name'];
$item_tree[$parent]['parent'] = $this->itemlist[$parent]['parent'];
$item_tree[$parent]['child'] = $this->get_tree($parent);
return $item_tree;
}
foreach ($this->itemlist as $key => $val)
{
if ($val['parent'] == $parent)
{
$item_tree[$key]['name'] = $val['name'];
$item_tree[$key]['parent'] = $val['parent'];
$item_tree[$key]['child'] = $this->get_tree($key);
}
}
return $item_tree;
}
function make_optionlist ($id, $class='', $delimiter='/')
{
$option_list = '';
$item_tree = $this->get_tree(0);
$options = $this->make_options($item_tree, '', $delimiter);
if (!is_array($id))
{
$id = array($id);
}
foreach($options as $row)
{
list($index, $text) = $row;
$selected = in_array($index, $id) ? ' selected="selected"' : '';
$option_list .= "<option value=\"$index\" class=\"$class\"$selected>$text</option>\n";
}
return $option_list;
}
function make_options ($item_tree, $before, $delimiter='/')
{
$before .= empty($before) ? '' : $delimiter;
$options = array();
foreach ($item_tree as $key => $val)
{
$options[] = array($key, '- '.$before.$val['name']);
if (!empty($val['child'])) {
$options = array_merge($options, $this->make_options($val['child'], $before.$val['name'], $delimiter));
}
}
return $options;
}
function get_navlinks ($navid, $tpl, $startlink='', $delimiter=' ยป ')
{
// $tpl typ: {name}
$search = array('{id}', '{name}');
$navlink = array();
while (isset($this->itemlist[$navid]))
{
$replace = array($navid, $this->itemlist[$navid]['name']);
$navlink[] = str_replace($search, $replace, $tpl);
$navid = $this->itemlist[$navid]['parent'];
}
if (!empty($startlink))
{
$navlink[] = str_replace($search, array(0, $startlink), $tpl);
}
$navlink = array_reverse($navlink);
return implode($delimiter, $navlink);
}
function show_tree ($parent=0, $tpl='%s', $ul_class='', $li_class='')
{
$item_tree = $this->get_tree($parent);
return $this->get_node($item_tree, $parent, $tpl, $ul_class, $li_class);
}
function get_node ($item_tree, $parent, $tpl, $ul_class, $li_class)
{
// $tpl typ: {name}
$search = array('{id}', '{name}');
$output = "\n<ul class=\"$ul_class\">\n";
foreach ($item_tree as $id => $item)
{
$replace = array($id, $item['name']);
$output .= "<li class=\"$li_class\">".str_replace($search, $replace, $tpl);
$output .= !empty($item['child']) ? "<br />".$this->get_node ($item['child'], $id, $tpl, $ul_class, $li_class) : '';
$output .= "</li>\n";
}
return $output . "</ul>\n";
}
function get_id_in_node ($id)
{
$id_list = array($id);
if (isset($this->itemlist[$id]))
{
foreach ($this->itemlist as $key => $row)
{
if ($row['parent'] == $id)
{
if (!empty($row['child']))
{
$id_list = array_merge($id_list, get_id_in_node($key));
} else
{
$id_list[] = $key;
}
}
}
}
return $id_list;
}
function get_parent ($id)
{
return isset($this->itemlist[$id]) ? $this->itemlist[$id]['parent'] : false;
}
function get_item_name ($id)
{
return isset($this->itemlist[$id]) ? $this->itemlist[$id]['name'] : false;
}
}
?>
Scenario:
Say you have the following structure in a :
Literature
-- Integration of sources
---- Test 1
It will result in the following in the database table:
When I try to delete this sublevel, it will leave the last sublevel in the database while it should delete it. The result will be:
The PHP code:
//Check if delete button is set
if (isset($_POST['submit-deletecategory']))
{
//Get $_POST variables for category id
$CategoryParent = intval($_POST['CategoryList']);
//Check if category is selected
if ($CategoryParent != "#")
{
//Get parent category and subsequent child categories
$query = "SELECT CID, Item AS Name, Parent FROM " . TB_CATEGORY . " ORDER BY Name";
$items = new ItemTree($query);
if ($items->get_item_name($_POST['CategoryList']) !== false)
{
//Build up erase list
$CategoryErase = $items->get_id_in_node($CategoryParent);
$CategoryEraseList = implode(", ", $CategoryErase);
}
else
{
$CategoryEraseList = 0;
}
//Remove categories from database
$query = "DELETE FROM " . TB_CATEGORY . " WHERE CID IN ($CategoryEraseList)";
$result = mysql_query($query) or die ('Database Error (' . mysql_errno() . ') ' . mysql_error());
//Return a confirmation notice
header("Location: settings.php");
exit;
}
}
Thank you in advance for any guidance I can get to solve the issue.
Here is a way to do it : use a recursive function, which will first look for the leaf item (the deepest in your tree). You remove children first, then the parent. And for each child, you remove child's children first, etc...
deleteSub(1);
function deleteSub($cat_id) {
$request = "SELECT * FROM ". TB_CATEGORY ." WHERE Parent = ".$cat_id;
$results = mysql_query($request);
while($child = mysql_fetch_array($results))
{
deleteSub($child["CID"]);
}
$request = "DELETE FROM ". TB_CATEGORY ." WHERE CID = ".$cat_id;
return mysql_query($request);
}
A better way could be use this kind of recursive function to store CIDs in an array, then make a single DELETE request, but I think you'll be able to adapt this code.
I'm not going to read or try to understand the entire code, but it seems to me you need some sort of recursion function. What I basicly would do is create a function that goes up in the hierachy and one that goes down.
Note: It has been a while since i've written anything in procedural mysql, so please check if the mysql_num_rows(),mysql_fetch_array and so on is written in the correct manner
EDIT: I've just noticed you only wanted a downwards deletion and therefore zessx's answer is more valid
<?php
function recursiveParent($id) {
$sql = 'SELECT parent FROM betyg_category WHERE CID=' . $id;
$result = mysql_query($sql);
if(mysql_num_rows($result) > 0) {
while($r = mysql_fetch_array($result,MYSQLI_ASSOC)) {
recursiveParent($r['parent']);
}
}
$sql = 'DELETE FROM betyg_category WHERE CID=' . $id;
mysql_query($sql);
}
function recursiveChild($parent) {
$sql = 'SELECT CID FROM betyg_category WHERE parent=' . $parent;
$result = mysql_query($sql);
if(mysql_num_rows($result) > 0) {
while($r = mysql_fetch_array($result,MYSQLI_ASSOC)) {
recursiveChild($r['CID']);
}
}
$sql = 'DELETE FROM betyg_category WHERE parent=' . $parent;
mysql_query($sql);
}
function delete($id) {
recursiveParent($id);
recursiveChild($id);
}
?>
This is my way to do. instead of recursive the query to run, i get all the child's id first then only run query. here the code refer:-
First, defined a variable called $delete_node_list as array. (to store all node id that need to be delete)
function delete_child_nodes($node_id)
{
$childs_node = $this->edirectory_model->get_child_nodes($node_id);
if(!empty($childs_node))
{
foreach($childs_node as $node)
{
$this->delete_child_nodes($node['id']);
}
}
$this->delete_node_list[] = $node_id;
}
in mysql..
$sql = 'DELETE FROM betyg_category WHERE CID IN '.$this->delete_node_list;
mysql_query($sql);
I am having a problem with making the links in my bar work properly the database is setup like so my db http://bloodkittens.com/resources/upload/db.png
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
mysql_connect("localhost", "dbuser", "******");
mysql_select_db("guild");
// prepare special array with parent-child relations
$menuData = array(
'items' => array(),
'parents' => array()
);
$result = mysql_query("SELECT id_menu id, parentID_menu parentId, label_menu name FROM main_menu` ORDER BY parentID_menu");
while ($menuItem = mysql_fetch_assoc($result))
{
$menuData['items'][$menuItem['id']] = $menuItem;
$menuData['parents'][$menuItem['parentId']][] = $menuItem['id'];
}
// menu builder function, parentId 0 is the root
function buildMenu($parentId, $menuData)
{
$html = '';
$parent='';
if (isset($menuData['parents'][$parentId]))
{
$menuClass= ($parentId==0) ? ' class="navbar" id="navbar"' : '';
$parent= ($parentId==0) ? 0 : 1;
$html = "<ul{$menuClass}>\n";
foreach ($menuData['parents'][$parentId] as $itemId)
{
//subment
$result=mysql_query("select * from main_menu where parentID_menu='$itemId'");
if (mysql_num_rows($result)>(int)0 && $parentId!=0) {
$subm =' class="navbar"';
}else{
$subm ='';
}
//end
$menu = $parentId == 0 ? ' class="menulink"' : ''; //class of main menu
$html .= '<li>' . "<a{$subm}{$menu} href=\"#\" >{$menuData['items'][$itemId]['name']}</a>";
// find childitems recursively
$html .= buildMenu($itemId, $menuData);
$html .= '</li>';
}
$html .= '</ul>';
}
return $html;
}
// output the menu
echo buildMenu(0, $menuData);
?>
How would i make it so that the value link_menu would be the href in the code for each separate entry in the db? rather then \'#\' because the code works completely and i'm very happy how it looks after i apply my css to it but the links aren't working
For work the menu sorting
must be add a new field in the table,
and change this query from
$result = mysql_query("SELECT id_menu id, parentID_menu parentId, label_menu name, link_menu link FROM main_menu ORDER BY parentID_menu");
to :
$result = mysql_query("SELECT id_menu id, parentID_menu parentId, label_menu name, link_menu link FROM main_menu ORDER BY menu_sort");
you never seem to select it
$result = mysql_query("SELECT id_menu id, parentID_menu parentId, label_menu, link_menu, name FROM main_menu ORDER BY parentID_menu");
and then..
$html .= '<li>' . "<a{$subm}{$menu} href=\"{$menuData['items'][$itemId]['link_menu']}\" >{$menuData['items'][$itemId]['name']}</a>";
Instead of href=\"#\" >, use this:
href=\"{$menuData['items'][$itemId]['link_menu']}\" >
the code that i used was in the end like this i think i got it to work by pure luck but regardless i win : )
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
mysql_connect("localhost", "BloodKittens", "Zangoshi1");
mysql_select_db("bloodkittens");
// prepare special array with parent-child relations
$menuData = array(
'items' => array(),
'parents' => array(),
'links' => array()
);
$result = mysql_query("SELECT id_menu id, parentID_menu parentId, label_menu name, link_menu link FROM main_menu ORDER BY parentID_menu");
while ($menuItem = mysql_fetch_assoc($result))
{
$menuData['items'][$menuItem['id']] = $menuItem;
$menuData['parents'][$menuItem['parentId']][] = $menuItem['id'];
$menuData['links'] = $menuItem['link'];
}
// menu builder function, parentId 0 is the root
function buildMenu($parentId, $menuData)
{
$html = '';
$parent='';
if (isset($menuData['parents'][$parentId]))
{
$menuClass= ($parentId==0) ? ' class="navbar" id="navbar"' : '';
$parent= ($parentId==0) ? 0 : 1;
$html = "<ul{$menuClass}>\n";
foreach ($menuData['parents'][$parentId] as $itemId)
{
//subment
$result=mysql_query("select * from main_menu where parentID_menu='$itemId'");
if (mysql_num_rows($result)>(int)0 && $parentId!=0) {
$subm =' class="navbar"';
}else{
$subm ='';
}
//end
$menu = $parentId == 0 ? ' class="menulink"' : ''; //class of main menu
$html .= '<li>' . "<a{$subm}{$menu} href=\"{$menuData['items'][$itemId]['link']}\" >{$menuData['items'][$itemId]['name']}</a>";
// find childitems recursively
$html .= buildMenu($itemId, $menuData);
$html .= '</li>';
}
$html .= '</ul>';
}
return $html;
}
// output the menu
echo buildMenu(0, $menuData);
?>