I am trying to print the different category's selected in a single line in xml,
like
<cat_name>meeting, food and drinks, sports</cat_name>
The output I am getting:
<cat_name>meeting, food and drinks, sports,</cat_name>
I want to remove only the last comma.
The code I have written so far is:
$sq="
select category_main.cat_name
from category_main
join category
on(category.cat_id=category_main.cat_id)
where category.event_id='$event_id'
";
$e=mysql_query($sq);
$xml ='<cat_name>';
while($row=mysql_fetch_array($e))
{
$res=$row['cat_name'];
//$new = substr($val,0,-1);
$xml .="$res, ";
}
$xml .='</cat_name>';
echo $xml;
Call trim() with the optional second parameter as a ','
trim($cat_name, ',')
However, since you're doing this in a while loop, you should build an array then implode() it rather than building the string in the loop. This avoids the extra comma to begin with.
$arr = array();
while($row=mysql_fetch_array($e))
{
$arr[] = $row['cat_name'];
}
$cat_name = implode(",", $arr);
// $cat_name is now "meeting, food and drinks, sports"
You can do this by [i used my variable]
$str = substr($str,0, (strlen($str)-1));
Or use a rtrim, rtrim( $cat , ',' ) http://php.net/rtrim
Related
I have an issue that I am stuck in,
I have a table called wpg_original_word with field tags, which contains comma separated values and what I want to achieve is search for tags which are starting with the letter 'd'
I have written the query
SELECT DISTINCT tags FROM wpg_original_word WHERE tags LIKE 'd%' ;
It returns the whole string like 'Diabetes, Nutrition, Dietician' , but I want only the Diabetes, Dietician.
Any help?
You could split the string with PHP, use the following code
<?php
$string = 'Diabetes, Nutrition, Dietician';
$array = explode(',', $string);
$result = array();
foreach ($array as $part) {
if (substr(strtolower(trim($part)),0,1) == 'd') {
array_push($result, trim($part));
}
}
var_dump($result);
See it in action here.
http://codepad.org/SVk7FPx9
You can use in_array() to check for a string in your query and then print it.
While executing this code from a webservice, the title and keywords are shown in the meta tags as expected. The description stays empty though. How do I put dynamic array content from $array in the description? Ps eg $array[3] won't work either.
$array = $result->AAAResult->AAA->A;
$teller = count($array);
$titeltekst = "{$teller} quantity: $r";
$doc =& JFactory::getDocument();
$options = $doc->getHeadData();
$options['title'] = $titeltekst;
$options['metaTags']['standard']['keywords'] = "keywords - test";
$options['metaTags']['standard']['description'] = $array;
$doc->setHeadData($options);
You wont be able to assign an array directly to anything that expects a string, but you can use implode assuming that all the values are also strings.
$string = implode(', ', $array);
Ok I just added eg.
$string .= $v->Naam;
and;
$options['metaTags']['standard']['description'] = $string;
, if you choose to create the string on the Naam (Name) object of the Array.
I have a MySQL field called "tags" an example result. The single field has a list of text with comma separated values.
A real example:
red, pants, shoes, heels, lookbook
I want to somehow use find and replace or implode feature to print out this row as separate links.
My guess so far:
<?php
$tag=$row["tags"];
whilst (!$tag=="") {
echo '$tag, "';
}
?>
split the comma separated list into an array using explode()
convert each element in the list to a link using foreach
convert the array to a comma separated list using implode()
example:
$tags = explode(", ", $row["tags"]);
foreach ($tags as &$tag) {
$tag = "$tag";
}
echo implode(", ", $tags);
Another approach would be using preg_replace:
$row['tags'] = "banana, apple, peach, strawberry";
echo preg_replace( '#([^,\s]+)#is',
'$1',
$row['tags']);
You should probably take a look at this answer first SQL Array Search (how to store such an information in the database). If you still want to use coma separated list, the best way is probably using explode(), array_map() and implode():
function generateLink( $tag){
$tag = htmlspecialchars( trim( $tag));
$str = "$tag";
}
$tags = explode( ',', $row['tags']);
$new_tags = array_map( 'generateLink', $tags);
echo implode( ', ', $new_tags);
// Of course you can chain it to:
echo implode( ', ', array_map( 'generateLink', explode( ',', $row['tags'])));
However if you use correct database design you should this SELECT (displaying one product):
SELECT tags.name
FROM tags_products
INNER JOIN tags ON tags_products.tag_id = tags.id
WHERE tags_products,product_id = ?
And with php:
$q = $db->query( 'mentioned select');
$result = array();
while( $row = $q->fetch_assoc()){
$result[] = genereateLink( $row['name']);
}
And in case of mass listing of product to increase performance use this select with GROUP_CONCAT:
SELECT products.id, products.name, GROUP_CONCAT(tags.name ASC SEPARATOR ', ') AS tags
FROM products
LEFT JOIN tags_products ON tags_producsts.product_id = products.id
INNER JOIN tags ON tags_products.tag_id = tags.id
GROUP BY products.id
And apply the first mentioned code on $row['tags'] :)
I would like some help in converting a string to an array and performing foreach on the array data.
Currently in my view I echo my string <?php echo $p['tags']; ?>
and this gives me the following data news, latest
I would like to do a foreach on this data so that I can wrap the values in
How is this done? What is the best method?
Explode them into an array:
<?php
$all_tags = explode( ',' , $p['tags'] );
foreach ( $all_tags as $one_tag ){
echo '' . $one_tag . '';
}
The explode() function splits the string using a delimiter (in this case the ',' comma) and each item is passed into the array.
I'm not sure I understand what you're asking correctly. Is this what you want?
$var = 'news, lastest';
$tmp = explode(', ', $var);
$result = ''.implode(', ', $tmp).'';
var_dump($result);
// string(42) "news, lastest"
hey there I have this,
$following_user_id .= $row['following_user_id'];
and I get
44443344330
then I use the implode() function and seperate with commans
44,44,33,44,33,0,
but I don't want the last comma on the last number?
Is this possible?
$following_user_ids = array();
//loop this:
$following_user_ids[] = $row['following_user_id'];
$user_ids_string = implode(',',$following_user_ids);
You can split the string into an array of characters, then implode the array.
$array = preg_split('//', $following_user_id, -1, PREG_SPLIT_NO_EMPTY);
echo implode( ',', $array );
Collect your data into an array of strings and use the implode function:
$uids = array();
while($row = mysql_fetch_assoc($result)){
array_push($uids, $row['following_user_id']);
}
$following_user_id = implode(',', $uids);
Check implode: http://php.net/manual/en/function.implode.php
Code example: I'm assuming your using some sort of loop?
$arrUsers = new array();
... your loop code here ...
array_push($arrUsers, $row['following_user_id']);
... end loop code ..
$following_user_id = impload(",", $arrUsers);
Implode should not be inserting a comma at the end of that string there. Are you sure there isn't an empty string at the end of your array sequence?
Either way, to fix the string you have, just get rid of the last character of the string:
$concatUserIds = "44,44,33,44,33,0,";
$concatUserIds = substr($concatUserIds, 0, strlen($concatUserIds) - 1);
Further, if you're not going to be using the non-comma delimited number set, why don't you just add a comma every time you add a user id. That way you don't even have to use the implode function.
This works for me:
<?php
$following_user_id.= $row['following_user_id'];
$following_user_id=preg_replace('/(?<=\d)(?=(\d)+(?!\d))/',',',$following_user_id);
echo $following_user_id."<br>";
?>
Try using arrays, example
<?php
$arr = array();
$arr[] = 'foo';
$arr[] = 'bar';
echo implode(',', $arr);