I have a database that have multiple fields. i've to display one of its field in in html table. i can do it easily. but the problem is that the field i want to show may contain repeated words in a row. for eg
now what i want to do is that i have to trim repeated words i.e if a word is more than once in a row so it should be displayed only once. e.g above will be
i.e i don't want to show repetition when displaying record in html table. i want to make it dynamic i.e not just for 5 to 6 word. but to condemn repetition even if there thousands of records.
considering whole value of a row as a string how could i remove this using php ..
Thanks for your support in advance..
$variable="mike;john;mike";
$each=explode(';',$variable);
//print_r($each);
$new=array_unique($each);
echo implode(';',$new); //mike;john
If you'll treat each line or row as a sentence you can split on the separator, the semicolon in your examples. So if "UD;RUP;UD;UD" is a line you do something like:
line = "UD;RUP;UD;UD";
lineArray = new Array();
lineArray=line.split(";");
Then you want to create a new array that will hold the unique values you parse from your string:
newArray = new Array();
Now you iterate over the first array and see if you already have it stored. If you don't, store it by pushing to your new array:
for(i=0;i<lineArray .length;i++)
{
if((i==lineArray .indexOf(lineArray [i]))||(lineArray .indexOf(arr[i])==lineArray .lastIndexOf(arr[i])))
newArray.push(lineArray [i]);
}
And finally join the newArray elements:
newArray.join(";");
You can try with this
<?php
$consulta=Array('azul,azul,verde,amarillo','verde','azul,verde','azul');
$arrall=Array();
foreach ($consulta as $value) {
$arrnew= explode(",", $value);
if(count($arrnew!=0)){
foreach ($arrnew as $value) {
array_push($arrall, $value);
}
}
}
$result = array_unique($arrall);
I would say, the key is to create a unique index for each record.
<?php
$records = array(
'john;mike;john',
'john',
'mike;sally;mike;mike'
);
foreach($records as $index => $record) {
$records[$index] = implode(';',array_unique(explode(';',$record)));
}
print_r($records);
?>
This is in plain JavaScript to show the concept
var records = [
'john;mike;john',
'john',
'mike;sally;mike;mike'
]
var tuple;
for(var r in records) {
var tuple = records[r].split(';');
var index = {};
for(var t in tuple) {
index[tuple[t]] = true;
}
records[r] = Object.keys(index).join(';');
}
console.log(records);
I hope this helps :)
Try this:
/**
* @param array|string $values
* @param string $delimiter
*
* @return bool|string
*/
function filterValues($values = array(), $delimiter = ';') {
if(is_string($values) && $values) {
$explodedValues = explode($delimiter, $values);
return implode($delimiter, array_unique($explodedValues));
} else if(is_array($values) && $values) {
return implode($delimiter, array_unique($values));
} else {
return false;
}
}
$string= 'mike;bike;mike';
$array = array('mike', 'bike', 'mike');
echo filterValues($string);
echo filterValues($array);