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

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.

Related

String from an array from an array from the database

Okay so, first of all, I searched through the www for this question, and I found some question related to arrays but not exactly to mine.
Okay so as you may know, paypal only allows one custom variable to be $POST but I need to gather the product id AND the quantity of the item bought. So to do this I made my custom variable into something that would get the post like (25-1,12-3,13-4) it means, the user bought 3 items(separated by commas), where the first number is the product id (then the separator '-' comes in) and the second one is the quantity. (so they're all in the same row and column)
Now my problem is displaying it from the database. I need to get the product name and details that's why I need to separate the numbers from each array as a string and fetch the data from the database for the information of the product. (I'm using an older version of php anyway, 5.2, I guess.)Now the problem is:
1.) It returns the word 'Array' (literally) so it would say like ArrayArrayArray
2.) How do I explode/separate those data so I can get it because I need the product ID to fetch some other data... I tried exploding it into array, then exploding it again but doesn't work (most likely my code is wrong?)
Here is my code: (I've already connected to the database)
$data = mysql_query("SELECT * from transactions") or die(mysql_error());
/* My table tag and headers goes here */
while($info = mysql_fetch_array( $data )) {
echo "<tr>";
echo '<td>' . $info['id'] . '</td>';
echo "<td>";
$array = $info['product_id_array'];
$explode_array = explode(",", $array);
foreach($explode_array as $explode_more){
$explode_more = explode("-", $explode_array);
$prod_id = $explode_more[0];
$quantity = $explode_more[1];
print_r($prod_id); //should echo the 25 in the array (25-1), right?
print_r($quantity);
}
echo"</td>";
echo"<tr>";
}
If only paypal would allow multiple custom variables T_T Thank you guys. Forgive me if I can't express my question very well or my language is not good, as english is not my first language :), Good day!
Your variable names are mixed up. Inside the foreach-loop, you should do something like this
foreach($explode_array as $explode_more){
$explode_even_more = explode("-", $explode_more);
$prod_id = $explode_even_more[0];
$quantity = $explode_even_more[1];
print_r($prod_id); //should echo the 25 in the array (25-1), right?
print_r($quantity);
}
Note, that $explode_more is used inside the loop and $explore_array is left as is.
Separate this in multiple tables, never store non-atomic values in 1 column.
Certainly not when they have relation with another table.
Suppose you want to know the sales from a certain product in some period.

Grab random value the remove from array

I am wanting to use a form confirmation to display a single use code and then discard the code so it wont be used again. So far this is what I have:
$codes = array(
'810',
'0190',
'1924',
'481',
'2941',
'8777',
'092',
'432',
'984',
'172',
'8483'
);
$rand_code = array_rand($codes);
$code_gen = $codes[$rand_code];
return $confirmation = 'Here is your code:' . $code_gen;
This shows me a random code each time I submit the form so it works perfect. I need to actually store that code and not use it again. What would be my best solution? Any help would be greatly appreciated.
Shuffle to get a random one, then pop it out, bam.
shuffle($codes);
while($code_gen = array_pop($codes)){
return $confirmation = 'Here is your code:' . $code_gen;
}
If you prepend the datetime to the ticketnumber then you are guaranteed that your number is not used again without needing to store it. (unless we have time travellers).
e.g. 110912032634 = ticket 1 and 110912032785 = ticket 2
If you mean by "later on" in the session, use sessions, etc...
If you mean by "later on" : after a month to collect data, then store it in a database

stop repetition of data displayed, foreach loop php, mysql

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

Zend Php Foreach Loop array

I have a input field and a array of email from DB table.
I am comparing the similarity of the input field to the array.
But some how, I am stuck with the loop.
Does that loop check compare each email with the input field?
It always bring me to google.com no matter what i input same or not
Here's the code from the controller:
if (isset($_POST['btn_free_download']))
{
// Get current input email from input field
$email = $this->getRequest()->getParam('email');
// Get all emails from the user
$referred_users = $this->_helper->user()->getReferredUsers()->toArray();
// Check the similarity which it with a loop
foreach ($referred_users as $referred_user)
{
similar_text($email, $referred_user['email'], $similar);
}
// If yes, Pop up message or redirect to some page
if ($similar < 97)
{
$this->_redirect('http://google.com');
}
// If not, redirect user to free download page
else
{
$this->_redirect('http://yahoo.com');
}
}
I think you need to check the manual . Foreach function is same wether you use it on zend or any other framework or raw php only.
$referred_users = $this->_helper->user()->getReferredUsers()->toArray();
$referred_users will probably hold an array of emails from the table
user, say:
$referred_users = array("one#email.com", "two#email.com", "three#email.com")
then when you use foreach loop it will iterate through each of the
emails in the array
foreach ($referred_users as $referred_user)
{
// for the first loop $referred_user = one#email.com, for second time $referred_user = two#email.com and goes on
similar_text($email, $referred_user['email'], $similar);
}
Now let us discuss your logic here:
// If yes, Pop up message or redirect to some page
if ($similar < 97)
{
$this->_redirect('http://google.com');
}
// If not, redirect user to free download page
else
{
$this->_redirect('http://yahoo.com');
}
Until and unless the last element in the array $referred_users is exactly equal to your $email
i.e. $email = "three#email.com"
you will always be given result for $similar less than 97% which means you will be redirected to google.
Which I assume you are not trying to do and probably not familiar with foreach function which is why you are not getting the expected result.
Assuming you are trying to do something like, check for the emails in the array if any of the email in the array matches (if array is from table check if the email entered from param is equal to any of the emails in the table) then redirect to somewhere or show some message else carry on. Solution below might be helpful to you.
$similarText = false;
foreach ($referred_users as $referred_user)
{
// for the first loop $referred_user = one#email.com, for second time $referred_user = two#email.com and goes on
similar_text($email, $referred_user['email'], $similar);
if ($similar > 97) {
$similarText = true;
break;
}
}
// If yes, Pop up message or redirect to some page
if ($similarText)
{
$this->_redirect('http://google.com');
}
// If not, redirect user to free download page
else
{
$this->_redirect('http://yahoo.com');
}
Hope you got the idea. But please do check the manual before posting a question in the future.

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.

Categories