Why not output the first element array? - php

Why not output the first element array?
i use next code
$product_idn='123112$2313213';
$count_products=substr_count($product_idn,'$')+1;
$idn_products=explode('$',$product_idn);
$name_products='';
$s=0;
while($s<=$count_products){
$prod=$idn_products[$s];
$res10=mysql_query("..... WHERE `product_idn`='$prod'");
$i10=mysql_fetch_assoc($res10);
$name_products.=$i10['name'].', ';
$s++;
}
echo $name_products;
//give 2313213,,
Why not output the first element array ?

What about
$product_idn='123112$2313213';
$idn_products=explode('$',$product_idn);
$name_products='';
foreach($idn_products as $val){
$res10=mysql_query("..... WHERE `product_idn`='$val'");
$i10=mysql_fetch_assoc($res10);
$name_products.=$i10['name'].', ';
}
echo $name_products;

There are a lot of unusual techniques being used in the original code. My best guess at what I'd do, without really knowing the purpose of this code is:
$product_idn = '123112$2313213';
$idn_products = explode('$', $product_idn);
$name_products = '';
foreach($product_idn as $value) {
$res10 = mysql_query("SELECT name FROM ... WHERE `product_idn`='$value'");
if ($res10) {
$i10 = mysql_fetch_assoc($res10);
$name_products .= $i10['name'].', ';
}
}
$name_products = rtrim(', ', $name_products);
echo $name_products;

Related

Concatenation of exploded array of tags to a string with links

With my custom function below, my aim is to give a specific link to each element of array of tags. My input to the function is a string like (tag1, tag2, tag3). My output is (in linked form) tag1,
“tag1,” is okey but why can not I get what I expect : “tag1, tag2, tag3” (in linked form)
I read examples in php.net and in this site for the terms (array, explode, for, .=) but I couldn’t solve my issue.
Can you guide me please
function tag_linkify ($article_tags)
{
$array_of_tags = explode(",", $article_tags);
$sayac = count($array_of_tags);
$linked_tags ="";
for ($i=0; $i<$sayac; $i++)
{
$linked_tags .= ''.$array_of_tags[$i].', ';
}
echo substr_replace($linked_tags, '', -1, 2);
}
tag_linkify (tag1,tag2,tag3);
ThanksRegards
Improving on Sedz post:
function tag_linkify ($article_tags)
{
$array_of_tags = explode(",", $article_tags);
echo '' . implode(',', $array_of_tags) . '';
}
tag_linkify ("tag1,tag2,tag3");
Btw. the parameters in your tag_linkify call miss their quotation marks and
'<a href="'.'">'
is really the same as
'<a href="">'
If i understand your question correctly i would do:
tag_linkify ($tag1, $tag2, $tag3);
function tag_linkify ()
{
$tags = get_func_args(); // get all tags in an array
$final = '';
// loop through the tags
forech($tags as $tag)
{
// return or echo depends on what you doing with your data
$final .=''. $tag . '';
}
return $final;
}
get_func_args
Check this out with use of implode
function tag_linkify ()
{
$array_of_tags = get_func_args();;
$sayac = count($array_of_tags);
$linked_tags =array();
for ($i=0; $i<$sayac; $i++)
{
$linked_tags[] = ''.$array_of_tags[$i].' ';
}
echo "(".implode(',', $lined_tags).")";
}
tag_linkify (tag1,tag2,tag3);
I hope this can help

Generate a set of HTML list items from a comma separated list? PHP

I have a field in my database with the text value:
"these, are, some, keywords" (minus the inverted commas)
Now, I wonder if I can generate an unordered list from this so ultimately my HTML reads:
<ul>
<li>these</li>
<li>are</li>
<li>some</li>
<li>keywords</li>
</ul>
Is this possible with PHP and if so is anyone able to help me out with this?
Many thanks for any pointers.
You can accomplish this with something like the following:
<?php
$yourList = "these, are, some, keywords";
$words = explode(',', $yourList);
if(!empty($words)){
echo '<ul>';
foreach($words as $word){
echo '<li>'.htmlspecialchars($word).'</li>';
}
echo '</ul>';
}
?>
As mentioned by elcodedocle, you may want to use str_getcsv() instead of explode if more appropriate.
Have a look at str_getcsv() and explode()
Example:
<?php
$mystring = "these, are,some , keywords";
$myvalues = str_getcsv($mystring);
$myoutput = "<ul>";
foreach ($myvalues as $value){
$myoutput .= "<li>".trim($value)."</li>\n";
}
$myoutput .= "</ul>";
echo $myoutput;
?>
You need to explode you string for ', '
print <ul>
for each element in the array you received you print '<li>' . $value . '</li>'
print </ul>
You can try:
$arr = explode(",","these, are, some, keywords");
$res = "<ul>";
foreach ($arr as $val){
$res .= "<li>" . $val . "</li>";
}
$res .= "</ul>";
echo $res;

$db->fetchAll($query) non-associative for loop through columns

I'm been hunting everywhere trying to find how to access data returned via a Zend db call. i want to append each columns value, comma delimited into a variable. I've always used associative calls in the past $row['fieldname'] etc.. but don't want to type out all the fields. I think I'm pretty close with the below but it's not working. Can someone point out my error? Thanks!
$data = $db->fetchAll($query);
$i=13; //number of columns
foreach($data as $row){
for($j=0;$j<$i;$j++) {
$csv_output .= $row[$j].", ";
}
$csv_output .= "\n";
}
Wow, you're over-complicating things! Try:
$csv_output = array();
foreach ($db->fetchAll($query) as $row)
{
$csv_output[] = implode(', ', $row);
}
$csv_output = implode("\n", $csv_output);
echo '<pre>';
print_r($csv_output);
echo '</pre>';

echo text separating every 3 words per line?

I have seen some samples using var_dump, but I I would rather use a simple echo, if it's possible.
It should look like this using echo:
This is a
simple text
I just wrote
Using var_dump:
function split3($text)
{
$array = array();
foreach(explode(' ',$text) as $i=>$word)
{
if($i%3) {
$array[floor($i/3)] .= ' '.$word;
} else {
$array[$i/3] = $word;
}
}
return $array;
}
$text = "This is a simple text I just wrote";
var_dump(split3($text));
Your sample output is a bit wrong compare to your question.
If the output is like this.
This is a
simple text I
just wrote
Then replace the var_dump(split3($text)); with this
$splitedText = split3($text);
foreach($splitedText as $value){ //Just print the array content
echo $value . "<br />"; //I use <br /> as a new line
}

White Space in Key of Associative Array PHP

I'm parsing out an HTML table and building an array based on the row values. My problem is the associative keys that are returned have a bit of white space at the end of them giving me results like this:
Array ( [Count ] => 6 [Class ] => 30c [Description] => Conformation Model (Combined 30,57) )
So a line like this:
echo $myArray['Count'];
or
echo $myArray['Count '];
Gives me a blank result.
for now I've got a pretty hacky work around going...
foreach($myArray as $row){
$count = 0;
foreach($row as $info){
if($count == 0){
echo 'Count:' . $info;
echo '<br>';
}
if($count == 1){
echo ' Class:' . $info;
echo '<br>';
}
if($count == 2){
echo ' Description:' . $info;
echo '<br>';
}
$count++;
}
}
The function I'm using to parse the table I found here:
function parseTable($html)
{
// Find the table
preg_match("/<table.*?>.*?<\/[\s]*table>/s", $html, $table_html);
// Get title for each row
preg_match_all("/<th.*?>(.*?)<\/[\s]*th>/", $table_html[0], $matches);
$row_headers = $matches[1];
// Iterate each row
preg_match_all("/<tr.*?>(.*?)<\/[\s]*tr>/s", $table_html[0], $matches);
$table = array();
foreach($matches[1] as $row_html)
{
preg_match_all("/<td.*?>(.*?)<\/[\s]*td>/", $row_html, $td_matches);
$row = array();
for($i=0; $i<count($td_matches[1]); $i++)
{
$td = strip_tags(html_entity_decode($td_matches[1][$i]));
$row[$row_headers[$i]] = $td;
}
if(count($row) > 0)
$table[] = $row;
}
return $table;
}
I'm assuming I can eliminate the white space by updating with the correct regex expression, but, of course I avoid regex like the plague. Any ideas? Thanks in advance.
-J
You can use trim to remove leading and trailing whitespace characters:
$row[trim($row_headers[$i])] = $td;
But don’t use regular expressions for parsing the HTML document; use a proper HTML parser like the Simple HTML DOM Parser or the one of DOMDocument instead.
An easy solution would be to change
$row[$row_headers[$i]] = $td;
to:
$row[trim($row_headers[$i])] = $td;

Categories