I have a wallposts MySql table with a tag_filter field, this field will have a comma seperated value.
I want to get all the unique/distinct tags for a user from this tag_filter field and populate in ul element.
There could be many posts per user.
eg
post1: tag_filter = a, b, c
post2: tag_filter = a, d, e
post3: tag_filter = c, d, e
the desired output would be
<ul>
<li>a</li>
<li>b</li>
<li>c</li>
<li>d</li>
</ul>
Here is my code thus far:
$tag_filter_list = mysql_query('SELECT tag_filter from wallposts where userid = '.$USER->id);
$list = "<ul>";
while ($tag_filter = mysql_fetch_array($tag_filter_list)) {
$value = $tag_filter["tag_filter"];
$info = explode(",", $value);
foreach( $info as $item ) {
$list.="<li>$item</li>\n";
}
}
$list .= "</ul>";
echo $list;
I would also like to populate a js var with the distinct/unique list acquired from the above.
var sampleTags = [
<?php
$tag_filter_list = mysql_query('SELECT tag_filter from wallposts where userid = '.$USER->id);
$all_tags = array();
while ($tag_filter = mysql_fetch_array($tag_filter_list)) {
$value = $tag_filter["tag_filter"];
$info = explode(",", $value);
$all_tags = array_merge($all_tags, $info);
}
$tags = array_unique($all_tags); // values will be sorted by the function
foreach( $tags as $item ) {
$list = "$item";
}
echo join(',', $list);
?>
];
This might help.
$tag_filter_list = mysql_query('SELECT tag_filter from wallposts where userid = '.$USER->id);
$tags = array();
while ($tag_filter = mysql_fetch_array($tag_filter_list)) {
$value = $tag_filter["tag_filter"];
$tags[] = explode(",", $value); // put all in an array
}
// now, join and remove duplicates and sort in ascending order
$tags = implode( ',', $tags );
$tags = explode( ',', $tags );
$tags = array_values( array_unique( $tags ) );
sort($tags);
$list = "<ul>";
foreach( $tags as $item ) {
$list .= "<li>$item</li>\n";
}
$list .= "</ul>";
echo $list;
Hope this helps.
Comma separated values in a MySQL field is a sign of a bad database design, linked tables should be used if possible.
However, in your case, the following code might work:
$all_tags = array();
while ($tag_filter = mysql_fetch_array($tag_filter_list)) {
$value = $tag_filter["tag_filter"];
$info = explode(",", $value);
$all_tags = array_merge($all_tags, $info);
}
$tags = array_unique($all_tags); // values will be sorted by the function
foreach( $tags as $item ) {
$list .= "<li>$item</li>\n";
}
To put all tags in a javascript variable:
<script type="text/javascript">
var sampleTags = [<?php echo explode(', ', $tags); ?>];
</script>
Try merging all tag_filter arrays with array_merge() and then use array_unique() to remove duplicates.
Just try with the following example :
<?php
$post_array = array('a,b,c','a,d,e','c,d,e');
$tag_list = '<ul>';
$i=0;
while($i < count($post_array)){
$filter_explode = explode(',',$post_array[$i]);
$filter_count = count($filter_explode);
for($j=0;$j<$filter_count;$j++)
{
if(!in_array($filter_explode[$j],$tag_list_build)){
$tag_list_build[] = $filter_explode[$j];
}
}
$i++;
}
$tag_list_build_count = count($tag_list_build);
for($k=0;$k<$tag_list_build_count;$k++)
{
$tag_list.= '<li>'.$tag_list_build[$k].'</li>';
}
$tag_list.= '</ul>';
echo $tag_list;
?>
I think this may help you to resolve your problem.
Related
$cats_array = array(1,7,28);
foreach ($cats_array as $category) {
$category_field_query = "SELECT fields
FROM categories
WHERE status = 1 AND id = $category";
$category_field_query_run = mysqli_query($connect, $category_field_query);
$cat_field = mysqli_fetch_object($category_field_query_run);
$field = explode(",", $cat_field->fields); /* Explode ',' from '/'3'/,' */
$field = str_replace("/","",$field); /* Delete all '/' */
print_r($field);
}
Inside foreach loop, my query returns something like that /7/,/13/,/24/ from fields for every turn, then I clean them from slashes and commas.
My goal is collect all that arrays inside one array.
I tried to create an empty array outside of foreach and sum all in it but it returned empty.
You have to be define $filed as a array before foreach loop. now you can store value into $filed. note that you have to multidimensional array required to store value.
$cats_array = array(1,7,28);
$field = array();
foreach ($cats_array as $category) {
$category_field_query = "SELECT fields FROM categories WHERE status = 1 AND id = $category";
$category_field_query_run = mysqli_query($connect, $category_field_query);
$cat_field = mysqli_fetch_object($category_field_query_run);
$field1 = explode(",", $cat_field->fields); /* Explode ',' from '/'3'/,' */
$field[] = str_replace("/","",$field1); /* Delete all '/' */
}
print_r($field);
I don't understand why do you store the fields like that, but here is a possible solution:
$fields = array();
$cats_array = array(1,7,28);
foreach ($cats_array as $category) {
$category_field_query = "SELECT fields FROM categories WHERE status = 1 AND id = $category";
$category_field_query_run = mysqli_query($connect, $category_field_query);
$cat_field = mysqli_fetch_object($category_field_query_run);
preg_match_all('/\/(\d+)\//', $cat_field->fields, $matches);
if (!empty($matches[1])) {
$fields = array_merge($fields, $matches[1]);
}
}
print_r($fields);
$fields = array();
$cats_array = array(1,7,28);
foreach ($cats_array as $category) {
$category_field_query = "SELECT fields FROM categories WHERE status = 1 AND id= $category";
$category_field_query_run = mysqli_query($connect, $category_field_query);
$cat_field = mysqli_fetch_object($category_field_query_run);
$field = explode(",", $cat_field->fields); // Explode ',' from '/'3'/,'
$field = str_replace("/", "", $field);
$fields[] = $field;
}
print_r($fields);
I really need some help with this code and I'm not that good at PHP.
Here is the code:
function projectAttr($number){
global $clerk, $project;
$projectid = $project['id'];
$tags = array();
$cleanUrls= (bool) $clerk->getSetting( "clean_urls", 1 );
$getTags = $clerk->query_select ( "projects_to_tags", "DISTINCT tag", "WHERE projectid='$projectid' ORDER BY id ASC" );
while ( $tag= $clerk->query_fetchArray( $getTags ) )
{
$tagset = explode('; ', $tag['tag']);
}
return html_entity_decode($tagset[$number]);
}
The code explodes a string and puts it in a array, that I can get by projectAttr(0). But I want to be more specific in what I want to get from the string.
This is my string:
size='large'; caption='short text about post/project'; bgcolor='black'; color='white';
What I want is, if I write projectAttr(size) it should return the value large and so forth.
Is that even possible?
Thanks, Peter
I'll answer specifically to the explode you want. You should modify your projectAttr function to look this this:
$items = explode('; ', $string);
$attr = array();
foreach($items as $item) {
list($key, $val) = explode('=', $item);
$attr[$key] = str_replace(array("'", ""), '',$val);
}
Which returns
Array (
[size] => large
[caption] => short text about post/project
[bgcolor] => black
[color] => white
)
EXAMPLE DEMO
So modify your function to look like this:
function projectAttr($name) {
global $clerk, $project;
$projectid = $project['id'];
$tags = array();
$cleanUrls = (bool) $clerk->getSetting("clean_urls", 1);
$getTags = $clerk->query_select("projects_to_tags", "DISTINCT tag", "WHERE projectid='$projectid' ORDER BY id ASC");
while ($tag = $clerk->query_fetchArray($getTags)) {
$items = explode('; ', $string);
$attr = array();
foreach ($items as $item) {
list($key, $val) = explode('=', $item);
$attr[$key] = str_replace(array("'", ""), '', $val);
}
}
return html_entity_decode($attr[$name]);
}
And that should allow you to call it like this:
projectAttr('size');
try
function projectAttr($number){
$str= "size='large'; caption='short text about post/project'; bgcolor='black'; color='white';";
$r = explode('; ', $str);
foreach($r as $k=>$v) {
$attr = explode('=', $v);
$projectAttr[$attr[0]] = str_replace("'", "", $attr[1]);
}
return html_entity_decode($projectAttr[$number]);
}
echo projectAttr('size'); // large
Hy every one I have this problem with an array I start like this...
$name = array($_POST['names']);
$nameId = array();
$query = mysql_query("SELECT id FROM types WHERE find_in_set (name, '$name')");
while($row = mysql_fetch_assoc($query)){
$nameId[] = array('ids' => $row['id'] );
}
which gives me arrays like this..
$name:
array('0'=>'name1,name2,name3')
$names:
array('0'=>array('ids'=>'61'), '1'=>array('ids'=>'6'), '2'=>array('ids'=>'1'))
how can I bring this in an string/form like this..
array('0'=>'61,6,1')
The idea is to save the ids to the Database.
Or is the a better more efficent way to get names from a form compare them with a database and get the ids back to save them to the Database?
many thanks in advance.
Change your assignment to this:
$nameId[] = $row['id'];
$name = array(name1,name2,name3);
$nameId = array();
$query = mysql_query("SELECT id FROM types WHERE find_in_set (name, '$name')");
while($row = mysql_fetch_assoc($query)){
//below line changed
$nameId[] = $row['id'] ;
}
$string = implode(',',$nameId);
Try this :
$array = array(0=>array(0=>'61'),1=>array(0=>'6'),2=>array(0=>'1'));
$result = implode(",",call_user_func_array('array_merge', $array));
Please note : Here all are numeric keys, so change your code to :
$nameId[] = array($row['id'] ); , remove key 'ids' from here
Output :
61,6,1
Thats what I think
$nameId[] = $row['id'];
$stringId = implode(',',$name);
Use following function that will loop through array and find ids key and merge it into other array and after that when you calling this function it will impload it.
function CustomFindJoinArray( $needly, $array )
{
$results = array();
foreach ( $array as $key => $value )
{
if ( is_array( $value ) )
{
$results = array_merge($results, foo( $needly, $value ));
}
else if ( $key == $needly )
{
$results[] = $value;
}
}
return $results;
}
echo implode( ",", CustomFindJoinArray( "ids", $your_array ) );
where $your_array will be array('0'=>array('ids'=>'61'), '1'=>array('ids'=>'6'), '2'=>array('ids'=>'1'))
OR More simple
foreach ($your_array as $key => $ids) {
$newArray[] = $array[$key]["ids"];
}
$string = implode(',', $newArray);
$ids = array();
foreach($nameId as $curr) {
$ids[] = $curr['ids'];
}
$str = "(".implode(",",$ids).")";
Hi I currently have this code that retrieves the tags from each Image in the Database. The tags are seperated by commas. I place each set of tags on the end of the array. Now I want to create an array of the tags retrieved but merge any duplications.
function get_tags()
{
$tag_array = array();
$query = mysql_query("
SELECT tags
FROM gallery_image
");
while($row = mysql_fetch_assoc($query))
{
$tags = $row['tags'];
$tag_array[] = $tags;
}
echo $tag_array[0] . '<br>' . $tag_array[1] . '<br>' .$tag_array[2];
}
You question is not very clear but array_unique may be what you need?
function get_tags()
{
$query = mysql_query('SELECT tags '.
'FROM gallery_image');
$tag_array = array();
while($row = mysql_fetch_assoc($query))
$tag_array = array_merge($tag_array, explode(',', $row['tags']));
return array_unique($tag_array);
}
You probably want something like this:
$tags = array(
'one,two',
'one,three',
);
$result = array_unique(array_reduce($tags,
function($curr, $el) {
return array_merge($curr, explode(',', $el));
},
array()));
See it in action.
What this does is process each result row (which I assume looks like "tag1,tag2") in turn with array_reduce, splitting the tags out with explode and collecting them into an intermediate array which has just one tag per element. Then the duplicate tags are filtered out with array_unique to produce the end result.
Try this:
$unique_tags = array();
foreach ($tag_array as $value) {
$unique_tags = array_merge($unique_tags, explode(",", $value);
}
$unique_tags = array_unique($unique_tags);
this is continued from another question i asked:
Listing out JSON data?
my search only returns 1 item, im pretty sure the problem lies somewhere in my php, im not too sure if im adding to the array properly, or it could be the javascript wich you can see on the above link, but i doubt it.
my php code:
function mytheme_ajax_response() {
$search = $_GET["search_text"];
$result = db_query("SELECT nid FROM {node} WHERE title LIKE '%s%' AND type = 'product_collection'", $search);
$noder = array();
while ($record = db_fetch_object($result)) {
$noder[] = $record;
}
$matches = array();
$i = 0;
foreach ($noder as $row) {
$node = node_load($row->nid);
$termlink = db_fetch_object(db_query("SELECT tid FROM {term_node} WHERE nid = %d", $row->nid));
$matches[$i]['title'] = $node->title;
$matches[$i]['link'] = $termlink->tid;
}
++$i;
$hits = array();
$hits['matches'] = $matches;
print json_encode($hits);
exit();
}
You appear to be incrementing your $i variable AFTER the foreach loop. Therefore, $i is always 0 throughout your loop, so you are always setting the title and link values for $matches[0].
Try this:
function mytheme_ajax_response() {
$search = $_GET["search_text"];
$result = db_query("SELECT nid FROM {node} WHERE title LIKE '%s%' AND type = 'product_collection'", $search);
$noder = array();
while ($record = db_fetch_object($result)) {
$noder[] = $record;
}
$matches = array();
foreach ($noder as $row) {
$node = node_load($row->nid);
$termlink = db_fetch_object(db_query("SELECT tid FROM {term_node} WHERE nid = %d", $row->nid));
$matches[] = array('title' => $node->title, 'link' => $termlink->tid);
}
$hits = array();
$hits['matches'] = $matches;
print json_encode($hits);
exit();
}
The $i wasn't incrementing the code as it was outside the foreach loop. By making a second array as above you don't need it anyway... (hope this works)...