stop repetition of data displayed, foreach loop php, mysql - php

I have a code which gives me list of addresses in my view file but some addresses are repeated. I don't want to display the ones which are already displayed.
$address_array[] = '-- Select address --';
foreach($address as $addres){
$address_array[$addres->id] = $addres->town;
}
Any idea on stopping the repetition?

With the in_array function, you can check if a value already exists in your array
$address_array[] = '-- Select address --';
foreach($address as $addres){
if (!in_array($addres->town, $address_array)) $address_array[$addres->id] = $addres->town;
}

Use array_unique to erase duplicates.
http://php.net/manual/en/function.array-unique.php
A little example :
$address = array_unique($address);

Related

How to echo multiple items from a single column on new line in PHP

I have two columns in my database that contain values entered from multiple select boxes. I used
$skills = join($_POST['skillSelect'],',');
$languages = join($_POST['languageSelect'],',');
to format them in the database. Now I want to display them to the user on a different page. They do display, but I want each on different lines. For example, let's say the user entered 'Java, PHP, JavaScript' as their language values. I want them to display as:
<p>Java</p>
<p>PHP</p>
<p>JavaScript</p>
However, they're just displaying as
Java, PHP, JavaScript
Here is my attempt using a foreach loop and explode:
<?php
$languages_explode = explode(PHP_EOL, $_SESSION['languages']);
foreach($languages_explode as $language) {
echo $language;
}
?>
I also tried:
echo "<p>".$language."</p>";
I thought the PHP_EOL delimiter would format it correctly, but I was wrong. How can I display each item on a new line, preferably within a paragraph tag? Thanks!
change this line
$languages_explode = explode(PHP_EOL, $_SESSION['languages']);
to
$languages_explode = explode(",", $_SESSION['languages']);
and then do
echo "<p>".$language."</p>";
try like this
your code from db is
Java, PHP, JavaScript
explode this to convert as array
$mystring = "Java, PHP, JavaScript";
$myArray = explode(',',$mystring);
//print_r($myArray);
foreach($myArray as $row)
{
echo "<p>".$row."</p><br>";
}

Trying to remove duplicate lines from array acc. to column contents

Using PHP and making a SELECT query from DB I am getting an output I don't like.
I start like this:
$details = Db::getInstance()->executeS($sql);
And I get, after a
echo json_encode($details);
For debug purposes:
[{"email":"test#on.gr","lastname":"TEST","firstname":"TEST1","id_lang":"1","id_order":"1"}]
[{"email":"test#on.gr","lastname":"OTHER","firstname":"DIFFERENT","id_lang":"1","id_order":"2"}]
[{"email":"test#on.gr","lastname":"THIRD","firstname":"DIFFERENT","id_lang":"1","id_order":"3"}]
[{"email":"new#on.gr","lastname":"THIRD","firstname":"NEW","id_lang":"1","id_order":"4"}]
What I want is to transform array $details to check on each "line" if the email column has unique values on the whole output. If yes to delete the lines that contain the duplicate entries and leave only the first that contain it.
Desired output:
[{"email":"test#on.gr","lastname":"TEST","firstname":"TEST1","id_lang":"1","id_order":"1"}]
[{"email":"new#on.gr","lastname":"THIRD","firstname":"NEW","id_lang":"1","id_order":"4"}]
(As you see lines with id order 2 and 3 where removed as they have the same email with the first)
Any kind of help will be highly appreciated.
Edit: just wanted to add up here that my code isn't in PHP. You have to change it.
Do an ORDER BY email command in the select statement.
Pseudo Code:
Loop through results:
String email1 = "";
String email2 = "";
for (i=0;i<(Detailssize); i++){
email2 = details[email][i]; //Do whatever you need to do to access the value of the email key here.
if(email2 != email1){
KEEP IT
}
else{
THROW AWAY
}
email1 = email2;
}
Obviously this is not PHP. It has been a while since i coded php. Nonetheless logically this should still work. I'm sure theres a way to change your SELECT statement to only return one from each value but i'm not good enough at SQL for that. This isn't as good of a solution but hope it helps.
Keep a list of emails you've seen before; whenever you encounter an email that has been seen before, skip that row.
Like this:
$newSet = array();
$seenBefore = array();
foreach( $details as $row ) {
if( isset( $seenBefore[ $row['email'] ) ) {
continue; // jump to the next row
}
// this email address must be new; add it to things we've seen before then add this row to the newSet
$seenBefore[$row['email']] = true;
$newSet[] = $row;
}
Then output $newSet in whichever way you want.

searching for a string while looping

I am trying to format another sites data to insert into my database. He wants to close his site, so is giving me his sites listings. But im having to format his data from his flatfile database, to go into my mysql database.
Im looping through his text file, and getting his values. Then formatting as needed before inserting them into my DB.
Because our sites use completely different storage formats and fields, im having a few problems with something.
My site has a designer field. His doesnt. so im trying to search through his description field to find a match within my designer table. If there is a match i want to get the designer ID to insert into the designer id field. But i cant get this code to work.
Could someone please suggest a fix? or if theres a better way to do this?
$fp = fopen('listings.txt','r');
if (!$fp) {echo 'ERROR: Unable to open file.'; exit;}
$loop = 0;
while (!feof($fp)) {
$loop++;
$line = fgets($fp,1024); //use 2048 if very long lines
$field[$loop] = explode (' ', $line);
$get_designers = mysql_query("SELECT * FROM dress_designers");
$row_designers = mysql_fetch_array($get_designers);
$totalRows_designers = mysql_num_rows($get_designers);
do{
// Note our use of ===. Simply == would not work as expected
// because the position of 'a' was the 0th (first) character.
$mystring = strtolower($field[$loop][8]);
$findme = strtolower($row_designers['designer_name']);
$pos = strpos($mystring, $findme);
// Note our use of ===. Simply == would not work as expected
// because the position of 'a' was the 0th (first) character.
if ($pos === false) {
$designer = "Other";
} else {
$designer = "Siopa Rince";
}
} while ($row_designers = mysql_fetch_assoc($get_designers));
$fp++;
}
fclose($fp);
I only put "Siopa Rince" as a test. But this isnt working. If i take the text from the file, and paste it in the $mystring and put siopa rince in $findme... it works.
Any suggestions would be greatly appreciated!
Thanks,
Danny
OK... what about just entering the info as is? I tried a few different ways, but the result is returning null...
After i insert the data, ill use searches to join the required row to get an ID:
SELECT dress_test.dress_title, (
SELECT dress_designers.designer_id
FROM dress_designers
WHERE MATCH (
dress_test.dress_desc
)
AGAINST (
'dress_designers.designer_name'
IN boolean MODE
)
) AS real_designer_id
FROM dress_test
Another version:
SELECT dress_test.dress_title, dress_designers.designer_name
FROM dress_test
JOIN dress_designers ON MATCH(dress_test.dress_title, dress_test.dress_desc) AGAINST
('dress_designers.designer_name' in boolean mode)
Any other suggestions??
Your first assignment to $row_designers uses mysql_fetch_array, while your second uses mysql_fetch_assoc
Instead of do { ... } while, why not just while () { ... }
Remove this line $row_designers = mysql_fetch_array($get_designers);
And turn your loop into...
while ($row_designers = mysql_fetch_assoc($get_designers)) {
// string search here
}
Everything else looks fine - if you're having troubles, check the values with either echo to print string or print_r to print arrays.

How To Stop Duplicates Being Listed On PHP Results?

I've made up a PHP script which assigns a score to listings on a website and assigns it to the results page. I have got it to work in that it shows the score and the details but it keeps listing the same results over and over.
I can't work out what it is doing but there is a small section of code I was hoping would prevent duplicate listings. Could anyone give it a tweak and see if I am going wring somewhere?
The Code is:
$dupCatch .= $adId.",";
$dupResults = explode(',', $dupCatch);
foreach($dupResults as $dupResult){
if($dupResult == $adId){
print "";
} else {
print $showResults;
$scoreBox = 'THIS IS THE SCORE: ' . $finalScore . '';
print $scoreBox;
}
}
Thanks in advance!
Jack
The problem is that you add your current $adId to the duplicate list before you check if it is there - which it will always be, of course.
Storing a bunch of numbers in a string, explodeing it every time, is a little weird, use an array instead. You also don't need to manually loop through all the items, just use in_array()
if( !in_array($adId, $dupCatch) ){
print $showResults;
$scoreBox = 'THIS IS THE SCORE: ' . $finalScore . '';
print $scoreBox;
}
$dupCatch[] = $adId;
Needless to say: it would be a better idea to fix the part that gives you the duplicate results in the first place.
You can either try to use array_unique from php side or use unique attribute at field in mysql this way duplicates can be prevent before even inserting them.

MODX parse error function implode (is it me or modx?)

Update 4-June-2010: This appears to be a bug in MODx v 1.0.3, nothing to do with the implode function but rather a problem with mis-matched datatypes in the resulting filter clause. Bug has been filed with JIRA: MODX-2035.
Hi, I cannot for the life of me figure this out, maybe someone can help.
Using MODX a form takes user criteria to create a filter and return a list of documents. The form is one text field and a few checkboxes. If both text field and checkbox data is posted, the function works fine; if just the checkbox data is posted the function works fine; but if just the text field data is posted, modx gives me the following error:
Error: implode() [function.implode]: Invalid arguments passed.
I've tested this outside of modx with flat files and it all works fine leading me to assume a bug exists within modx. But I'm not convinced. Here's my code:
<?php
$order = array('price ASC'); //default sort order
if(!empty($_POST['tour_finder_duration'])){ //duration submitted
$days = htmlentities($_POST['tour_finder_duration']); //clean up post
array_unshift($order,"duration DESC"); //add duration sort before default
$filter[] = 'duration,'.$days.',4'; //add duration to filter[] (field,criterion,mode)
$criteria[] = 'Number of days: <strong>'.$days.'</strong>'; //displayed on results page
}
if(!empty($_POST['tour_finder_dests'])){ //destination/s submitted
$dests = $_POST['tour_finder_dests'];
foreach($dests as $value){ //iterate through dests array
$filter[] = 'searchDests,'.htmlentities($value).',7'; //add dests to filter[]
$params['docid'] = $value;
$params['field'] = 'pagetitle';
$pagetitle = $modx->runSnippet('GetField',$params);
$dests_array[] = ''.$pagetitle.'';
}
$dests_array = implode(', ',$dests_array);
$criteria[] = 'Destinations: '.$dests_array; //displayed on results page
}
if(is_array($filter)){
$filter = implode('|',$filter);//pipe-separated string
}
if(is_array($order)){
$order = implode(',',$order);//comma-separated string
}
if(is_array($criteria)){
$criteria = implode('<br />',$criteria);
}
echo '<br />Order: '.$order.'<br /> Filter: '.$filter.'<br /> Criteria: '.$criteria;
//next: extract docs using $filter and $order, display user's criteria using $criteria...
?>
The echo statement is displayed above the MODX error message and the $filter array is correctly imploded.
Any help will save my computer from flying out the window.
Thanks
I think your problem lies here :
$dests_array = implode(', ',$dests_array);
$dest_array may be empty and not even initialized if $dests is empty.
This really should be posted in the MODx forums. I love stackoverflow, but MODx is more niche.

Categories