PHP create option list from delimited string without duplicating values - php

I have a string with values (which are suburbs) like so:
$suburbs = "Mawson, Elizabeth, Burnside, Elizbeth, Mawson";
There COULD be double ups in the suburbs that the string contains. I can't change this fact.
What I am trying to do is create an option list for a drop down menu that a user will use. I do not want to display the same suburb twice( or more for that matter).
What I have so far:
$suburbs = "Mawson, Elizabeth, Burnside, Elizbeth, Mawson";
//Explode the suburbs string delimited by a comma
$boom = explode(',', $suburbs);
foreach($boom as $b)
{
$suburbOptionList .= '<option value='.$b.'>'.$b.'</option>';
}
?>
<select> <?php
echo $suburbOptionList;
?>
</select>
I know that this will simply display all of the options but I really don't know how to display each suburb only once. Ive tried a few foreach,and if combinations but they look ugly and work just as bad.
Any help would be appreciated.
Cheers in advance!

Pass $boom through array_unique() and you'll be fine.
$bada_boom = array_unique($boom);
P.S.: This will not help if you have typos or variations in duplicates. (Elizbeth != Elizabeth).
In that case you will need to get creative.
Also, hw (in comments) made a good point about trimming whitespaces. If the suburbs come from an untrusted source and are improperly formatted, you may need to normalize them. This means trimming whitespaces and normalizing capitals:
$boom = array_walk($boom, 'trim');
$boom = array_walk($boom, 'strtolower');
$bada_boom = array_unique($boom);

Related

Extract a full substring from a partial substring (needle)

As you can see below, I'm attempting to extract the complete substring of an exploded array by using just a few characters to match the substring.
$keyword = array('Four Wheel', 'Power', 'Trailer');
function customSearch($keyword, $featurelistarray){
$key = ''; //possibly reset output
foreach($featurelistarray as $key => $arrayItem){
if( stristr( $arrayItem, $keyword ) ){
$termname = $key;
}
}
}
The array ($featurelistarray) comprises vehicle options, four wheel drive, four wheel disc brakes, power windows, power door locks, floor mats, trailer tow package, and many many more.
The point is to list all the options for a given category, and using the $keyword array to define the category.
I would also like to alphabetize the results. Thank you for the help!
To further explain, the $featurelistarray is exploded from a CSV field. The CSV field has a long length of options listed.
$featurelist=$csvdata['Options'];
$featurelistarray=explode(',',$featurelist);
$termname = $featurelistarray[0];
As you can see, $termname is assigned the first position of the exploded array. This was the original code for these features, but I need more control for $termname.
It seems to me you are trying to make database operations without database. I'd suggest to transform input into some kind of database.

Splitting an external array to give different titles

I've been trying to figure out how to split the array and add different titles for each of the separate titles on the page, for each of the different things that this displays. However the most I can manage to do is add a comma between the numbers and words.
I would like to add selling"1st variable price"second variable" etc however I don't quite know how to do anything other than to turn this very confusing looking bunch of letters:
user name and notes 01001000013972583957ecCCany amount-w378- v west
into anything other than this:
0,100,10000,1397258395,7ec,CC,any amount-w378- v west
Also, this is what it looks like in its JSON form:
{"selling":"0","quantity":"100","price":"10000","date":"1397258395","rs_name":"7ec","contact":"CC","notes":"any amount-w378- v west"}
I just want all the information that is in there to displayed like that however I'm not quite sure how to add the titles that is in the JSON data. I also don't have access to the external site to change anything.
A little background: what I am trying to achieve is a price look-up for a game on my website from an external site. I tried to use an iframe but it was terrible; I would rather just manually display it rather than showing their site from mine - their style and my style clash terribly.
$json = file_get_contents('http://forums.zybez.net/runescape-2007-prices/api/rune+axe');
$obj = json_decode($json,true);
$blah1 = implode( $obj[0]["offers"][1]);
print_r($blah1);
If you know where it is, you should be able to just grab it and show it out?
You can use a failsafe to check if it is present with is_array() and isset() functions - see php.net docs on them.
Your print_r should give you good valid info -- try to wrap it around <pre></pre> tags before for better readability or view the source - it will be easier!
<pre><?php print_r($obj) ?></pre>
This should be your starting point, and from here you will either take the first one of your items or loop through all with
foreach ($obj as $o) { //should be $objects, not $obj
//do whatever with $o, like echo $o['price']
}
Each offers row is a table with each field separated by row:
$item = json_decode(file_get_contents('http://forums.zybez.net/runescape-2007-prices/api/rune+axe'));
while ($offer = array_shift($item[0]->offers)) {
echo "<table>" . PHP_EOL;
foreach ($offer as $field => $value) {
echo "<tr><th>$field</th><td>$value</td></tr>" . PHP_EOL;
}
echo "</table>" . PHP_EOL;
}
http://codepad.org/C3PQJHqL
Tables in HTML:
http://jsfiddle.net/G5QqZ/

escape spaces in id attributes or deleting them in php section

i get different string (like a, b, hospital, schools, jobs to work etc. ) as $divname from my db in my PHP section. i use this values as id in mydiv elemnents.
<div id="'.$divname.'"></div>
there is no problem for $divname = a, b, hospital or school but when it comes to jobs to work there is a huge problem cause my id gets spaces and it returns an error to me.
<div id="jobs to work"></div> //as evryone state spaces in id variable is an error.
now my question i need use this $divame variables in my id attribute. how can i do this? how can i delete those spaces or any more idea for using those in id attributes are welcome.
You may do two things:
Use a hashing function to create new id, which will be unqiue as long as your ids are unique as:
$newdivid = md5($olddivid);
You may write a function to remove spaces and combine such string items
function remove_spaces($str) {
$str_arr = explode(' ', $str);
$newstr = "";
foreach($str_arr as $sitem){
$newstr .= trim($sitem);
}
return $newstr;
}
Hope this solves your problem.
i found a php command in another Sof question for this purpose
$new_divname = str_replace(' ', '', $divname);
it deletes all spaces.. and of course my question gets a dublicate:

Additional elements to URLS?

I'm not sure what the terminology is, but basically I have a site that uses the "tag-it" system, currently you can click on the tags and it takes the user to
topics.php?tags=example
My question is what sort of scripting or coding would be required to be able to add additional links?
topics.php?tags=example&tags=example2
or
topics.php?tags=example+example2
Here is the code in how my site is linked to tags.
header("Location: topics.php?tags={$t}");
or
<?php echo strtolower($fetch_name->tags);?>
Thanks for any hints or tips.
You cannot really pass tags two times as a GET parameter although you can pass it as an array
topics.php?tags[]=example&tags[]=example2
Assuming this is what you want try
$string = "topics.php?";
foreach($tags as $t)
{
$string .= "tag[]=$t&";
}
$string = substr($string, 0, -1);
We iterate through the array concatenating value to our $string. The last line removes an extra & symbol that will appear after the last iteration
There is also another option that looks a bit more dirty but might be better depending on your needs
$string = "topics.php?tag[]=" . implode($tags, "&tag[]=");
Note Just make sure the tags array is not empty
topics.php?tags=example&tags=example2
will break in the back end;
you have to assign the data to one variable:
topics.php?tags=example+example2
looks good you can access it in the back end explode it by the + sign:
//toplics.php
<?php
...
$tags = urlencode($_GET['tags']);
$tags_arr = explode('+', $tags); // array of all tags
$current_tags = ""; //make this accessible in the view;
if($tags){
$current_tags = $tags ."+";
}
//show your data
?>
Edit:
you can create the fron-end tags:
<a href="topics.php?tags=<?php echo $current_tags ;?>horror">
horror
</a>

Remove values in comma separated list from database

I have a table in my MySQL database called 'children'. In that table is a row called 'wishes' (a comma separated list of the child's wishlist items). I need to be able to update that list so that it only removes one value. i.e. the list = Size 12 regular jeans, Surfboard, Red Sox Baseball Cap; I want to remove Surfboard.
My query right now looks like this
$select = mysql_query('SELECT * FROM children WHERE caseNumber="'.$caseNum.'" LIMIT 1 ');
$row = mysql_fetch_array($select);
foreach ($wish as $w) {
$allWishes = $row['wishes'];
$newWishes = str_replace($w, '', $allWishes);
$update = mysql_query("UPDATE children SET wishes='$newWishes' WHERE caseNum='".$caseNum."'");
}
But the UPDATE query isn't removing anything. How can I do what I need?
Using these user-defined REGEXP_REPLACE() functions, you may be able to replace it with an empty string:
UPDATE children SET wishes = REGEXP_REPLACE(wishes, '(,(\s)?)?Surfboard', '') WHERE caseNum='whatever';
Unfortunately, you cannot just use plain old REPLACE() because you don't know where in the string 'Surfboard' appears. In fact, the regex above would probably need additional tweaking if 'Surfboard' occurs at the beginning or end.
Perhaps you could trim off leading and trailing commas left over like this:
UPDATE children SET wishes = TRIM(BOTH ',' FROM REGEXP_REPLACE(wishes, '(,(\s)?)?Surfboard', '')) WHERE caseNum='whatever';
So what's going on here? The regex removes 'Surfboard' plus an optional comma & space before it. Then the surrounding TRIM() function eliminates a possible leading comma in case 'Surfboard' occurred at the beginning of the string. That could probably be handled by the regex as well, but frankly, I'm too tired to puzzle it out.
Note, I've never used these myself and cannot vouch for their effectiveness or robustness, but it is a place to start. And, as others are mentioning in the comments, you really should have these in a normalized wishlist table, rather than as a comma-separated string.
Update
Thinking about this more, I'm more partial to just forcing the use of built-in REPLACE() and then cleaning out the extra comma where you may get two commas in a row. This is looking for two commas side by side, as though there had been no spaces separating your original list items. If the items had been separated by commas and spaces, change ',,' to ', ,' in the outer REPLACE() call.
UPDATE children SET wishes = TRIM(BOTH ',' FROM REPLACE(REPLACE(wishes, 'Surfboard', ''), ',,', ',')) WHERE caseNum='whatever';
Not exactly a direct answer to your question, but like Daren says it's be better having wishes as its own table. Maybe you could change your database schema so you have 3 tables, for instance:
children
-> caseNum
-> childName
wishes
-> caseNum
-> wishId
-> wishName
childrensWishes
-> caseNum
-> wishId
Then to add or delete a wish for a child, you just add or delete the relevant row from childrensWishes. Your current design makes it difficult to manipulate (as you're finding), plus leaves you at risk for inconsistent data.
As a more direct answer, you could fix your current way by getting the list of wishes, explode() 'ing them, removing the one you don't want from the array and implode() 'ing it back to a string to update the database.
Make wishes table have this format:
caseNumber,wish
Then you get all of a child's wishes like this:
SELECT * FROM children c left join wishes w on c.caseNumber = w.caseNumber WHERE c.caseNumber= ?
Removing a wish becomes:
DELETE from wishes where caseNumber = ?
Adding a wish becomes:
INSERT into wishes (caseNumber,wish) values (?,?)
Returning one wish becomes:
SELECT * FROM children c left join wishes w on c.caseNumber = w.caseNumber WHERE c.caseNumber= ? LIMIT 1
Having the wishes indexed in an array which is thereafter serialized could be an idea, otherwise you would need to retrieve the string, slice it, remove the part you don't want, then concatenate the remains. This can be done by using the explode() function.
If you were to use an array, you would retrieve the array and then sort through it with a loop like this:
// Wishes array:
// Array (
// [0] Regular Jeans
// [1] Surfboard
// [2] Red Sox Baseball Cap
// )
$wishes = $row['wishes']; // This is a serialized array taken from the database
$wishes = unserialize($wishes);
foreach ($wishes as $key => $value) {
if ($value == 'Surfboard') {
unset($wishes[$key]);
break;
}
}
$wishes = serialize($wishes);
// Update database
Keep in mind that index [1] now won't exist in the array, so if you wish to have a clean array you should loop through the array and make it create a new array by itself:
foreach ($wishes as $wishes) {
$newArray[] = $wishes;
}
I think the best answer to such issue is here
The best way to remove value from SET field?
query should be like this which covers the ,value or value, or only value in the comma separated column
UPDATE yourtable
SET
categories =
TRIM(BOTH ',' FROM
REPLACE(
REPLACE(CONCAT(',',REPLACE(col, ',', ',,'), ','),',2,', ''), ',,', ',')
)
WHERE
FIND_IN_SET('2', categories)
Here you can have your condition in where clause. for more details refer above link.
You can create function like this:
CREATE FUNCTION `remove_from_set`(v int,lst longtext) RETURNS longtext CHARSET utf8
BEGIN
set #lst=REPLACE(#lst, ',,', ',');
set #lng=LENGTH(#lst) - LENGTH(REPLACE(#lst, ',', ''))+1;
set #p=find_in_set(#v,#lst);
set #l=SUBSTRING_INDEX( #lst, ',', #p-1);
set #r=SUBSTRING_INDEX( #lst, ',', #p-#lng);
IF #l!='' AND #r!='' THEN
return CONCAT(#l,',',#r);
ELSE
RETURN CONCAT(#l,'',#r);
END IF;
END
Using:
SELECT remove_from_set('1,,2,3,4,5,6',1)

Categories