How do i merge matching strings in an array? - php

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);

Related

How I coul get a JSON like this?

I need to get a JSON with arrays, how I could do it?
//JSON I need to get
{"keywords":[{"keyword":"kw1", "tags":["sample"]},{"keyword":"kw2", "tags":["sample, sample2"]}]}
//For now, I got this
$keywords = array("kw1", "kw2");
$tags= array("sample", "sample2");
function Keywords($keywords, $tags){
$fields= array("keywords" => $keywords);
$jsondata = json_encode($fields);
print_r($jsondata );
}
//output
{"keywords":["kw1","kw2"]}
I expect the output like this:
{"keywords":[{"keyword":"kw1", "tags":["sample"]},{"keyword":"kw2", "tags":["sample, sample2"]}]}
Assuming tags in the first element of your example is supposed to be ["sample, sample2"] as well (otherwise you would really have to explain by what logic you want to achieve at the result as shown) …
$keywords = array("kw1", "kw2");
$tags= array("sample", "sample2");
$result = new StdClass;
$result->keywords = [];
foreach($keywords as $keyword) {
$temp = new StdClass;
$temp->keyword = $keyword;
$temp->tags = [];
foreach($tags as $tag) {
$temp->tags[] = $tag;
}
$result->keywords[] = $temp;
}
echo json_encode($result);
Basically two nested loops over the keywords and the tags, and inside a new temporary object is created an then appended to the result array.

Get unique value from an array php

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

get unique tags and number of occurrences from mysql using php

there is a "post" table in mysql and column "tags".
Tags' value is like apple,orange,peach,etc.
I'm trying to get all the tags and assign tag & number of occurances to array using php. Here is what I am trying to do.
$recmostusedtagscol = array();
$recmostusedtagsq = mysqli_query($connecDB,"select tags from post limit 5");
while($recmostusedtagsr = mysqli_fetch_array($recmostusedtagsq)){
$tagsarray = explode(',', $recmostusedtagsr['tags']);
foreach ($tagsarray as $tag) {
if(in_array($tag,$recmostusedtagscol)){
$recmostusedtagscol[$tag][]++;
}
else {
$recmostusedtagscol .= [$tag => 1];
}
}
}
print_r($recmostusedtagscol);
UPDATED:
this one is close. It is listing uniqe values, but it is not adding plus 1 to the array value.
$recmostusedtagscol = array();
$recmostusedtagsq = mysqli_query($connecDB,"select tags from post");
while($recmostusedtagsr = mysqli_fetch_array($recmostusedtagsq)){
$tagsarray = explode(',', $recmostusedtagsr['tags']);
foreach ($tagsarray as $tag) {
if(in_array($tag,$recmostusedtagscol)){
$recmostusedtagscol[$tag]++;
}
else {
$recmostusedtagscol[$tag]=1;
}
}
}
print_r($recmostusedtagscol);
it seems in_array() is not working.... maybe....
Based on the comments, here is the working one.
$recmostusedtagscol = array();
$recmostusedtagsq = mysqli_query($connecDB,"select tags from post");
while($recmostusedtagsr = mysqli_fetch_array($recmostusedtagsq)){
$tagsarray = explode(',', $recmostusedtagsr['tags']);
foreach ($tagsarray as $tag) {
if(isset($recmostusedtagscol[$tag])){
$recmostusedtagscol[$tag]++;
}
else {
$recmostusedtagscol[$tag]=1;
}
}
}
Thanks to #Mark Baker and #arkascha

Create a list like array when echoed in php

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 ']';

Change a PHP array into separate strings

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);

Categories