$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]);
Related
I want to display only unique strings and I have this code:
$sql = "SELECT tags FROM videos";
$result = mysqli_query($mysqli, $sql);
while ($rez = $result->fetch_assoc()) {
$array = array_filter(explode(',', $rez['tags']));
$array = array_unique($array);
foreach ($array as $value) {
$value = ltrim($value);
$value = str_replace(" ", "-", $value);
echo '' . $value . '<br>';
}
}
I have put an array_unique like this:
$array = array_unique($array);
But it returns this:
word-word
word
word2
word3
word-word
It doesn't print only unique values. What is wrong?
Think the problem is because the strings are being processed after the array_unique operation rather than before it. Try the following instead:
$sql = "SELECT tags FROM videos";
$result = mysqli_query($mysqli, $sql);
while ($rez = $result->fetch_assoc()) {
$array = array_filter(explode(',', $rez['tags']));
foreach ($array as $value) {
$value = ltrim($value);
$value = str_replace(" ", "-", $value);
}
$array = array_unique($array);
foreach ($array as $value) {
echo '' . $value . '<br>';
}
}
I have resolved, i will post code may be will be good for someone!
$sql = "SELECT tags FROM videos";
$result = mysqli_query($mysqli, $sql);
$alltags=array();
while ($rez = $result->fetch_assoc()) {
$array = array_filter(explode(',', $rez['tags']));
foreach ($array as $key => $value) {
$value = ltrim($value);
$value = str_replace(" ", "-", $value);
$alltags[]=$value;
}
}
$array=array_unique($alltags);
foreach ($array as $value) {
echo '' . $value . '<br>';
}
Explode your string.
Trim outer spaces from each element.
Replace inner spaces with hyphen in each element.
Only keep non-empty elements.
Only keep unique elements (using double array_flip).
Display results.
Code: (Demo)
while($rez=$result->fetch_assoc()) {
$array=explode(',',$rez['tags']); // split into elements
foreach($array as $v){
$v=str_replace(" ","-",trim($v)); // remove outer spaces, replace inner spaces
if($v){$clean[]=$v;} // retain non-empty values
}
$clean=array_flip(array_flip($clean)); // double flip is faster than array_unique
foreach($clean as $v){
echo "$v<br>";
}
}
Alternatively, you could do all of the value and html prep in the first foreach loop and then use implode to display the batch. This will remove the potentially unnecessary trailing from final element:
Code:
$rez['tags']=' , word , word-word, word2 , word word, word3,';
$array=explode(',',$rez['tags']); // split into elements
foreach($array as $v){
$v=str_replace(" ","-",trim($v)); // remove outer spaces, replace inner spaces
if($v){
$clean[]="$v"; // prep non-empty values for display
}
}
echo implode("<br>",array_unique($clean));
Output:
word<br>
word-word<br>
word2<br>
word3
I cannot solve this seeming simple problem. I have the following simple code and all I want is to echo the result of $ATL5_Alert_query and separated by a comma (,):
$ATL5_Alert_query = mysql_query("SELECT `Mobile` FROM `dbo_tech_name` WHERE `AlertLevel`= 1");
$dataset = array();
while ($data = mysql_fetch_array($ATL5_Alert_query))
{
$dataset[] = $data;
}
echo implode (",", $dataset);
However, I'm getting "Notice: Array to string conversion "...
In your code $data is array as well, so $dataset becomes an array of arrays, which you cannot concatenate. You should get the searched value by this:
while ($data = mysql_fetch_array($ATL5_Alert_query))
{
$dataset[] = $data['Mobile'];
}
or:
while ($data = mysql_fetch_array($ATL5_Alert_query))
{
$dataset[] = $data[0];
}
or:
while ($data = mysql_fetch_assoc($ATL5_Alert_query))
{
$dataset[] = $data['Mobile'];
}
If you however cannot change this, and already have your $dataset array, you can implode it like that:
echo implode(',', array_map(function($a){
return $a['Mobile'];
},$dataset));
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);
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;
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)...