I have an array returned from sql and I need to get them into separate strings to use on the page. It is out of a single row in the database and lists all the folders a user has.
example in database john has a red folder, green folder, blue folder.
I run the query and use fetchAll to return john's folders. I have it in an array. I can echo the array and it outputs redfoldergreenfolderbluefolder
How can I take the array and split it into separate strings?
PHP code
$query = "SELECT album_name FROM albums WHERE username = :username";
$query_params = array(
':username' => $email
);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
echo 'Database Error, please try again.';
}
$rows = $stmt->fetchAll();
foreach ($rows as $row) {
$post = array();
$post["album_name"] = $row["album_name"];
echo $post["album_name"]; // This just lists all albums together no spaces or commas
}
$text = implode(",", $post);
echo $text; // This just outputs the last item (bluefolder)
The below needs correction :
foreach ($rows as $row) {
$post = array();
$post["album_name"] = $row["album_name"];
echo $post["album_name"]; // This just lists all albums together no spaces or commas
}
$text = implode(",", $post);
echo $text; // This just outputs the last item (bluefolder)
Change the above to :
$post = array();
foreach( $rows as $row )
{
// $post = array(); // This line should not be here . It should be outside and above foreach
// The below echo is for test purpose . Comment it if you don't need it
echo $row["album_name"] ,' ';
// $post["album_name"] = $row["album_name"]; // This keeps assigning $row["album_name"] to same index "album_name" of $post . Eventually you will have only one value in $post
$post[] = $row["album_name"];
}
// $text = implode(",", $post); // With coma's as separator
$text = implode(" ", $post); // With blank's as separator
echo 'John has ' , $text;
try print_r($post); on your last line.
please use print_r($text) in side the for each and then you will get all the arry with commos
and remove $post = arry from there and put above of foreach.
i am trying to help you,may this help
thanks
anand
Try this:
$post = array();
foreach ($rows as $row) {
array_push($post, 'album_name', $row["album_name"]);
}
$text = implode(",", $post);
echo $text;
No assoc ver:
$post = array();
foreach ($rows as $row) {
$post[] = $row["album_name"];
}
$text = implode(",", $post);
echo $text;
The reason why it only show the last folder is because you do "$post = array()" at the beginning of your loop. It reset the array everytime... just take it out of the loop and put it above the foreach.
1: http://php.net/manual/en/function.imThe reason why it only show the last folder is because you do "$post = array()" at the beginning of your loop. It reset the array everytime... just take it out of the loop and put it above the foreach.
EDIT:
Try it this way :
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
$post = array();
foreach ($rows as $key => $folder) {
array_push($post, $folder)
}
$text = implode(",", $post);
Related
I Want To Get ID From Link i have set all links in array and explode forward slash / and then loop it but i'm getting only one id main link in array
"/4tzCuIpHHhc/long-title-here", i need this id 4tzCuIpHHhc
i'm trying this
<?php
$links = array(
"/WSNINQJZj1s/weightlifting-fairy-kim-bok-ju-ep05-lee-sung-kyung-run-nam-joo-hyuk-errand-20161130",
"/Nmy5FWgX0S0/weightlifting-fairy-kim-bok-ju-ep05-nam-joo-hyuk-reject-a-proposal-20161130",
"/u3gumA7-38A/weightlifting-fairy-kim-bok-ju-ep05-did-you-fall-in-love-with-my-brother-20161130",
"/Zsa_saeRT1E/weightlifting-fairy-kim-bok-ju-ep05-sung-kyung-offered-joo-hyuk-a-deal-20161130",
"/9q0uUfSr0lE/weightlifting-fairy-kim-bok-ju-ep05-nam-joo-hyuks-angry-at-lee-sung-kyung-20161130",
"/UH6YqMDdMDE/weightlifting-fairy-kim-bok-ju-ep05-sung-kyung-and-lee-jae-yoons-drive-date-20161130",
"/5pC2NJtCg_I/weightlifting-fairy-kim-bok-ju-ep03-did-you-fight-because-of-me-20161123",
"/UbxbVugdIdo/weightlifting-fairy-kim-bok-ju-ep01-lee-sung-kyung-fell-into-the-pool-20161116",
"/f29SpSqcOQc/weightlifting-fairy-kim-bok-ju-ep03-lee-sung-kyung-got-into-trouble-20161123",
"/ydWm_Pnp1BQ/weightlifting-fairy-kim-bok-ju-ep04-lee-sung-kyung-vs-nam-joo-hyuk-20161124",
"/uiLlQSexJr4/weightlifting-fairy-kim-bok-ju-ep01-an-underwear-thiefs-identity-20161116",
"/4tzCuIpHHhc/weightlifting-fairy-kim-bok-ju-ep01-weightlifter-vs-rhythmic-gymnast-20161116",
"/QzRi9_4-ItQ/weightlifting-fairy-kim-bok-ju-ep05-lee-sung-kyung-enter-a-contest-instead20161130",
);
foreach ($links as $result) {
$explode_c = explode('/',$result);
$s = $explode_c[1];
}
echo $s;
?>
Make $s as array
foreach ($links as $result) {
$explode_c = explode('/',$result);
$s[] = $explode_c[1];
}
print_r($s);
You can do like this, replace your with below:
$links = array(
"/WSNINQJZj1s/weightlifting-fairy-kim-bok-ju-ep05-lee-sung-kyung-run-nam-joo-hyuk-errand-20161130",
"/Nmy5FWgX0S0/weightlifting-fairy-kim-bok-ju-ep05-nam-joo-hyuk-reject-a-proposal-20161130",
"/u3gumA7-38A/weightlifting-fairy-kim-bok-ju-ep05-did-you-fall-in-love-with-my-brother-20161130",
"/Zsa_saeRT1E/weightlifting-fairy-kim-bok-ju-ep05-sung-kyung-offered-joo-hyuk-a-deal-20161130",
"/9q0uUfSr0lE/weightlifting-fairy-kim-bok-ju-ep05-nam-joo-hyuks-angry-at-lee-sung-kyung-20161130",
"/UH6YqMDdMDE/weightlifting-fairy-kim-bok-ju-ep05-sung-kyung-and-lee-jae-yoons-drive-date-20161130",
"/5pC2NJtCg_I/weightlifting-fairy-kim-bok-ju-ep03-did-you-fight-because-of-me-20161123",
"/UbxbVugdIdo/weightlifting-fairy-kim-bok-ju-ep01-lee-sung-kyung-fell-into-the-pool-20161116",
"/f29SpSqcOQc/weightlifting-fairy-kim-bok-ju-ep03-lee-sung-kyung-got-into-trouble-20161123",
"/ydWm_Pnp1BQ/weightlifting-fairy-kim-bok-ju-ep04-lee-sung-kyung-vs-nam-joo-hyuk-20161124",
"/uiLlQSexJr4/weightlifting-fairy-kim-bok-ju-ep01-an-underwear-thiefs-identity-20161116",
"/4tzCuIpHHhc/weightlifting-fairy-kim-bok-ju-ep01-weightlifter-vs-rhythmic-gymnast-20161116",
"/QzRi9_4-ItQ/weightlifting-fairy-kim-bok-ju-ep05-lee-sung-kyung-enter-a-contest-instead20161130",
);
foreach ($links as $result) {
$explode_c = explode('/',$result);
$s[] = $explode_c[1]; // made array of exploded string
}
echo "<pre>";
print_r($s);
$result = array_search('4tzCuIpHHhc', $s); // search for the string if you need key from $s
echo $id = $s[11];// $result = 11
$reply[$c] Contains "123 123 123" How can i convert so $reply[$c] equals 123\n123\n123
echo str_replace(' ',"\n",explode("\n", $reply[$c]));
My code that failed ^
Here is the code showing how $reply[$c] was formed and used im pretty new to php.
Quick code reference:
if (mysql_num_rows($result) > 0) {
//Fetch Results from Mysql (Store in an accociative array, because they wont be in the right order)
$rows = array();
while ($row = mysql_fetch_array($result,MYSQL_ASSOC)) {
$rows[$row['id']] = $row;
}
//Call Sphinxes BuildExcerpts function
if ($CONF['body'] == 'excerpt') {
$docs = array();
foreach ($ids as $c => $id) {
$docs[] = "'".mysql_real_escape_string(strip_tags($rows[$id]['body']))."'";
}
$result = mysql_query("CALL SNIPPETS((".implode(',',$docs)."),'{$CONF['sphinx_index']}','".mysql_real_escape_string($q)."')",$sphinxql);
$reply = array();
while ($row = mysql_fetch_array($result,MYSQL_ASSOC)) {
$reply[] = $row['snippet'];
}
}
foreach ($ids as $c => $id) {
$row = $rows[$id];
print ($reply[$c]); //Need to replace spaces with new lines here
}
}
Full code reference: http://nearby.org.uk/sphinx/search-example5-sphinxql.phps
You don't need to explode your string. Just replacing the spaces with newlines is enough.
echo str_replace(' ', "\n", $reply[$c]);
I would like to echo my results from a database and have them look like an array. They don't necessarily have to be an array but look like one. i.e. When i echo my result,
i would want my final result to look like
[10,200,235,390,290,250,250]
When i try the code below:
$query_rg = mysqli_query($link, "SELECT column FROM `table`");
$row_rg = mysqli_fetch_assoc($query_rg);
echo '[';
while ($row = mysqli_fetch_assoc($query_rg)) {
$list = $row['column'];
$listwithcoma = "$list,";
echo ltrim($listwithcoma,',');
}
echo ']'
The result is :
[10,200,235,390,290,250,250,]
You are doing it wrong. ltrim($listwithcoma,',') has no effect.
ltrim — Strip whitespace (or other characters) from the beginning of a string
You can try a simple way with implode.
$list = array();
while ($row = mysqli_fetch_assoc($query_rg)) {
$list[] = $row['column'];
}
echo '[' . implode(',', $list) . ']';
Just use GROUP_CONCAT in query as
$query_rg = mysqli_query($link, "SELECT GROUP_CONCAT(`column` SEPARATOR ', ') as data
FROM `table`");
$row_rg = mysqli_fetch_assoc($query_rg);
print_r($row_rg['data']);
Try like this
$list = array(); //define a array.
while ($row = mysqli_fetch_assoc($query_rg)) {
$list[] = $row['column']; //store column value in array.
}
$lists = "[".implode(",",$list)."]";
echo $lists; //will echo your results.
You should be using rtrim() function instead, that too outside the loop.
$listwithcoma = '';
echo '[';
while ($row = mysqli_fetch_assoc($query_rg)) {
$list = $row['column'];
$listwithcoma .= "$list,";
// echo ltrim($listwithcoma,','); Remove this
}
echo rtrim($listwithcoma,','); // Add this
echo ']';
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);
I am trying to build a list separated by commas which should look like this (green, orange, red).
$i=0;
$taxonomy = $form_state[values][taxonomy][5];
foreach ($taxonomy as $key => $value){
$result = db_query("SQL CODE goes here");
if (mysql_num_rows($result)){
while ($i<mysql_num_rows($result)){
$resultset = db_fetch_array($result);
$comma_separated = implode(",", $resultset);
$i++;
}
form_set_error("Date", t("$comma_separated. cannot be booked more than once "));
}
$resultset=array();
while ($data = db_fetch_array($result)) {
$resultset[] = $data;
}
$comma_separated = implode(",", $resultset);
Someone posted it and I was going to upvote, but they removed it. I think mysql GROUP_CONCAT would be a good solution, since it looks like getting a comma separated list is the only purpose of this query.
Try this:
$i=0;
$taxonomy = $form_state[values][taxonomy][5];
$result='';
foreach ($taxonomy as $key => $value)
{
$result = db_query("SQL CODE goes here");
if (mysql_num_rows($result)){
while ($row = mysql_fetch_row()){
result.=$row[0].',';
}
}
}
result=substr($result,0,-1);
echo $result;