PHP - Removing Duplicate Entries In A 2 Dimensional Array
I dont even know where to begin doing this. I am supposed to remove duplicate entries in this 2 dimensional array but I just can't find any answers anywhere.
Code: [Select] <?php /* In the following two dimensional array (an array of arrays) you will notice that there are several duplicate entries (David and Patricia). 1) Write a basic function which will go through $input and remove the duplicate entries. A "duplicate" is an entry which has the same FirstName and LastName as another entry. Ignore the other fields. Call your function "dedupe1". It should return a two-dimensional array without these duplicates 2) Using your dedupe1 function, write one called dedupe2 which will detect empty DOB's and DOB's of '00/00/0000'. When an empty or zeroed DOB is detected, your code should use the entry with a complete DOB (if available). Like dedupe1 your code should return a two-dimensional array without duplicates. If you use the provided $input function, all of the returned entries should have a complete DOB listed. */ $input = array( array( 'FirstName' => 'Daniel', 'LastName' => 'Anderson', 'Phone' => '614-123-4568', 'Address' => '123 Main St', 'SSN' => '001-01-0001', 'DOB' => '01/11/1922' ), array( 'FirstName' => 'Aaron', 'LastName' => 'Williams', 'Phone' => '937-321-3993', 'Address' => '933 N Park St', 'SSN' => '992-23-1192', 'DOB' => '04/21/1965' ), array( 'FirstName' => 'David', 'LastName' => 'Taylor', 'Phone' => '223-293-9921', 'Address' => '123 Main St', 'SSN' => '003-19-2992', 'DOB' => '12/14/1995' ), array( 'FirstName' => 'Patricia', 'LastName' => 'Anderson', 'Phone' => '614-123-4568', 'Address' => '123 Main St', 'SSN' => '123-32-3123', 'DOB' => '00/00/0000' ), array( 'FirstName' => 'David', 'LastName' => 'Taylor', 'Phone' => '223-293-9921', 'Address' => '123 Main St', 'SSN' => '003-19-2992', 'DOB' => '' ), array( 'FirstName' => 'Patricia', 'LastName' => 'Anderson', 'Phone' => '614-123-4568', 'Address' => '123 Main St', 'SSN' => '123-32-3123', 'DOB' => '02/22/1957' ), ); // Get results from dedupe1 and print them $result1 = dedupe1($input); var_dump($result1); // Get results from dedupe2 and print them $result2 = dedupe2($input); var_dump($result2); print_r($input);//just to see the information in the web page function dedupe1($in_array) { // your code here } function dedupe2($in_array) { // your code here } ?> Similar TutorialsI am quite new so I am sure this is an easy fix for some of the experts around here. I am using the canned script below to add urls to the database as text. The problem is if you update one of the form text boxes it loads all the urls into the database again resulting in a lot of duplicates. My question is, How do I get the form to only post the new changes and not re-post the existing urls? <?php session_start(); if(isset($_SESSION['userSession']) && !empty($_SESSION['userSession'])) { include_once("dbc.php"); if($_POST) { $c = 0; $errMssg = ""; for($i=0;$i<count($_POST['url']);$i++) { if($_POST['url'][$i]=="") { $c++; } } if($c==5) { $errMssg = "Submission error . Please fill at least 1 url."; } else { for($j=0;$j<count($_POST['url']);$j++) { if(!empty($_POST['url'][$j])) { $sql = mysql_query("INSERT INTO images (id ,url ,user_id)VALUES (NULL , '".$_POST['url'][$j]."',".$_SESSION['userId'].")"); } } } } $sqlresult = mysql_query("SELECT * FROM images WHERE user_id =".$_SESSION['userId']); $count = 0; while($data = mysql_fetch_array($sqlresult)) { $image[$count] = $data['url']; $count++; } ?> Hi Guys, This is a new post based on my last post for the same but I've revamped the code a little from the last post since I couldn't get it to work even with the suggestions, so my new code is below... Basically I have an updates table (updates_all) and a subscriptions table (subscriptions) and in the updates table items are entered for multiple users with querydate which increases based on the unix timestamp of the update. The Subscriptions table holds the data for users who are subscribed to other user's profiles. My issue is to show a logged in user his subscriptions and when a user he is subscribed to has a new update that user shows up on top of the list of his users. With the code below, i've been able to list the contents of the updates table, filter out the profiles which he is not subscribed to, and order the results by the most recent querydate. My question now is how do I run the while loop so it filters out all but one result per/member name?? Results output below the code... Code: [Select] $sql_findsubs = "SELECT * FROM updates_all ORDER BY auto_id DESC"; $rs_findsubs = mysql_query($sql_findsubs); $subscripPID = array(); $sql="SELECT * FROM subscriptions WHERE memberid='$id' "; $rs=mysql_query($sql); while($row=mysql_fetch_array($rs)) { $subscripPID[] =$row['profileid']; } while($rowfs = mysql_fetch_assoc($rs_findsubs)) { $id = $rowfs['id']; if (in_array($id, $subscripPID)) { echo $rowfs['auto_id'].' - '.$rowfs['querydate'].'.......'.$rowfs['member']; echo '<br>'; } } RESULTS: So if John is subscribed to Bob, Mary, Jim and Andy, I want to only show the four rows below, not all the other entries because those have a smaller querydate for those members. AutoID - Querydate - Name 130 - 1109092040.......Bob <-------- I want to show this one only for Bob 129 - 1109092039.......Bob 128 - 1109091935.......Bob 98 - 1106162306.......Mary <-------I want to show this one only for Mary 97 - 1106162254.......Mary 96 - 1106162215.......Jim <-------I want to show this one only for Jim 90 - 1105062043.......Bob 89 - 1105052200.......Andy <------I want to show this one only for Andy 88 - 1105052154.......Bob 87 - 1105052154.......Bob 86 - 1105052038.......Bob 80 - 1105052034.......Andy 79 - 1105052032.......Andy 73 - 1105052023.......Bob 72 - 1105052018.......Andy 60 - 1103192354.......Bob 4 - 1103172045.......Bob Any help is greatly appreciated... Thanks. I've run into a little bit of a logistical nightmare on some registration pages I've taken over work on. On these pages, parents register their kids for classes. The pages have been coded as such: page one: the user enters name and personal info, and selects one or two classes to register for, on submit, they go to page two. page two: their info is entered into the mysql database's registration table on a unique id The user verifies the total, enters a discount and submits page three: credit card info is added to registration table, and sent to authorize.net. page four: payment processed, and they enter the data for their kids into the attendees table page five: confirmation and done. My issue is that, at first I saw people entering page one data, going to page two, then for some reason, hitting the back button. They could then enter the data again. I'd have two entries in the registration table for the same person. I was going to put some sort of unique key on the name and an email, but then I saw scenario two... Another person enters data and registers one kid.. then for whatever personal reason goes back and registers a second kid in a completely separate transaction. So I can't put that key on there, but is there a way to prevent them from going back and reentering twice. I don't want to have to blow up the code to do it at the end of everything. and that would take implementing sessions, wouldn't it? I'm not so versed at that. Any thoughts? Hello, i am inserting some form data into my mysql db, i happen to get some duplicates so i want to check first if the entry exists already before i insert. my current code: Code: [Select] <?php if(isset($_POST['submit'])) { ?> <?php if (strlen($_POST['code']) == 19 && substr($_POST['code'],0,7) == '5541258') { mysql_query("INSERT INTO table(code,secret,ip,date) VALUES('$_POST[code]','$_POST[secret]','$_SERVER[REMOTE_ADDR]',CURDATE())"); Print "<font color='green'>The code will be checked now</font>"; } else { Print "<font color='red'>The code is invalid</font>"; } ?><?php } ?> I would like to use the value 'code' to check if the entry exists, that one is unique for each entry. How would i do that ? Thanks ! The only 2 tables relevant to what I want to do are "User" and "Scores." Basically this database holds high scores for a project I've been working on. I only want to display 10 scores, all from different users. No 2 or more scores from the same user. This is my db structure within phpmyadmin: Quote database -> table -> X / User / Score / X / X / X / X / X / X / X / X If possible I'd like to run a query where it checks for duplicate entries by the same user and only show the highest score. The current query I'm running is below: $result = mysql_query("SELECT * FROM table ORDER BY Score DESC LIMIT 0, 10"); Is this possible? I can only seem to find information regarding the INSERT IGNORE clause and that obviously won't help me as the users and scores are already in the database. Thanks. Hi all,
Its been a long time since last help request from real professional from here but I'm again in trouble with a much more spectacular plan I'm working on. For those who are interested in the plan then here it is: My Idea was to make a new build starting from scratch and make it as dynamical as possible. So my goal is not to make almost anything fixed in the code. I have made a decision to make a one supper large table for multiple different entries so no more joining and no more views for me.! In this help request I'm having trouble with Posting values to a page processing page lets call it record_changer.php The sole purpose of this file is to get form posts and decide what to do. Either update, delete, or insert. record_changer.php <?php include '../../config/config.inc.php'; if(is_ajax()){ # Checks if action value exists if(isset($_POST["action"]) && !empty($_POST["action"])){ $action = $_POST["action"]; # Switch case for value of action switch($action){ case "insert": datatable_insert_function(); break; case "update": datatable_update_function(); break; case "delete": datatable_delete_function(); break; } } } # Function to check if the request is an AJAX request function is_ajax(){ return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'; } function datatable_insert_function(){ } function datatable_update_function(){ } function datatable_delete_function(){ } ?>The problem. The problem is that the $insert places two entries to the DB. I cant seem to understand why.? # Test _POST values $_POST['UserID'] = '2'; $_POST['WorkID'] = '22'; $_POST['Status'] = '1'; $_POST['Code'] = '1'; $_POST['Title'] = '1'; $columns = array(); foreach(array_keys($_POST) as $name){ # Exclude Action and ID if($name == 'Action' || $name == 'ID' || $name == 'submit' ){ continue; } $columns[] = $name; } print_r($columns); echo "<br>"; $data = array_fill_keys($columns, 'NULL'); print_r($data); foreach($data as $key => $value){ $data[$key] = empty($_POST[$key]) ? 'NULL' : "'".mysql_real_escape_string($_POST[$key])."'"; } echo "<br>"; print_r($data); $insert = mysql_query('INSERT INTO datatable (ID, '.implode(', ',$columns).')VALUES (null, '.implode(',',$data).')') or die(mysql_error());No errors no nothing. Just two entries of correct data. PS. Sorry for a lot of prints in the code it is work and idea in the progress. The posts at the moment are fixed in the code so it is easier to refresh and debug. Please help if you spot the problem. Im really out of ideas. Some fresh eyes might make a difference. And Please for those who want to say it is a bad idea and why and why and so on.. Move a long.!!! Im not interested in whinging i have a great use for this and just having trouble with the two entries. Thanks. Edited by ztimer, 14 January 2015 - 03:27 PM. MySQL returns an error in the form of a number, a state, and a message. Without parsing the message you will not be able to determine what column is duplicated.While parsing the error code, I have also notice that, if you have multiple unique fields as duplicates, only the first duplicate encountered will be returned in the message. This is not very helpful to the end user.
Is there any way to parse the returned error code to reflect all duplicate fields, please see sample code below?
$error=array(); $sql = 'INSERT INTO staff(username, email, phone) VALUES (?, ?, ?)'; $stmt = $conn->stmt_init(); $stmt = $conn->prepare($sql); // bind parameters and insert the details into the database $stmt->bind_param('sss', $username, $email, $phone); $stmt->execute(); if ($stmt->errno == 1062) { $errors[] = "One of the fields is already in use."; } I have a for loop which extracts info from a MySQL table, chooses something then needs to push each bit into an array: for($i = 0 ; $i < $query_report_rows ; ++$i) { $row= mysql_fetch_row($query_names); if($row[6] == 0) { $sName = $row[1]; } elseif($row[6] == 1) { $sName = $row[2]; } $name = "$row[0], $sName"; $print = nl2br($row[7]); } What i need is a multidimensional array to hold $name and $print: $name_print = array( array('name'=>$name 'print'=>$print ) ) How do i array push into such an array from the above for loop? (multi-dimensional array are a very weak point at the moment, so any pointers here would be very much appreciated) Hiya peeps! Here are my scripts; test.php <?php include 'formValidation.php'; $new = new formValidation( array( array( 'formname' => 'firstname', 'value' => 'james', 'options' => 'required, alllowercase, onlyletters', 'name' => 'First Name' ), array( 'formname' => 'password', 'value' => 'blahblah', 'options' => 'required, oneuppercase, alphanumerical', 'name' => 'Password' ), array( 'formname' => 'username', 'value' => 'blahblah', 'options' => 'required, oneuppercase, alphanumerical', 'name' => 'Username' ) ) ); ?> formValidation.php <?php class formValidation { private $inputs; function __construct($inputs = array()) { foreach($inputs as $input_key => $input_value) { foreach($input_value as $key => $value) { echo $value . '<br />'; } } } public function __prep($formname, $options, $value, $name) { echo $formname . ' ' . $options . ' ' . $value . ' ' . $name . '<br />'; } } ?> This outputs; firstname james required, alllowercase, onlyletters First Name password blahblah required, oneuppercase, alphanumerical Password username blahblah required, oneuppercase, alphanumerical Username But what i need to do is for every four values I need them to be sent to the __prep function. EG; $this->__prep('firstname', 'required, alllowercase, onlyletters', 'james', 'First Name'); I have no idea how to do this tho, I have tried a for() loop, another foreach loop, array the first four values then foreaching them again. I'm stuck, someone please help! Many thanks, James. hello freaks,
I have a four-element array, which is the result of a mysql query. The array is like below. (This is of course just a snippet to show the structure; the hours of course go up to 24, then repeat; there are about ten days' worth of data.)
Array ( [dayname] => day1 [hour] => 1 [widtype] => type1 [Output] => 20 ) Array ( [dayname] => day1 [hour] => 2 [widtype] => type1 [Output] => 9 ) Array ( [dayname] => day1 [hour] => 1 [widtype] => type2 [Output] => 450 ) Array ( [dayname] => day1 [hour] => 2 [widtype] => type2 [Output] => 650 ) I want to loop through this data and output each hour's data in a separate line, like below (I included the headings just for clarity): Day Hour Type1_total Type2_total day1 1 20 450 day1 2 9 650 ... and can't seem to make this happen. Here's the code I've written: $prevday = ''; while ( $row = mysql_fetch_assoc($result)) { extract($row); $currentday = $row['dayname']; $currenthour = $row['hour']; $currentwid = $row['widtype']; while($currentday !== $prevday){ for($currenthour = 1; $currenthour <=24; $currenthour++){ if($row['widtype'] == 'type1'){ $type1_total = $row['Output'];} if($row['fuel'] == 'type2'){$type2_total = $row['Output'];} print "<pre>"; echo "$currentday, $currenthour, $type1_total, $type2_total"; print "</pre>"; } $prevday = $currentday; } }... and here's what it outputs: day1, 1, 20, , day1, 2, 20, , Clearly I have written this loop wrong but have banged my head against it for a while and wonder if it's just not possible to do what I want. Any suggestions would be hugely appreciated! I have been trying to solve this problem for a few days now and can't seem to work it out. I'm sure i'm missing some simple point.. I am using a mysql PDO fetch to return 2 fields in each row and then put them into an array of their own: foreach ($st->fetchAll() as $row){ $subs[] = array($row['subscriber'],$row['plant']); Some of the rows share the same $row[0], which is the 'subscriber' field. What I want to do is make up another array with each smaller array having a single, unique $row[0] and any number of added 'plant' fields following (e.g $row[1],$row[2] etc). I've tried all sorts of ways to achieve this but am at a loss. Would someone be able to point me in the right direction ? Thanks. I am having a hell of a time getting this to work. I need the keys in an array to be specific, not a sequential number or a row in my database. I need to add to the array through each loop of my while() statement. This code does it, but does not use the keys I specify, after the first entry, it starts assigning numbers to keys. Any guidance would be great. <?php require_once ('includes/config.php'); require_once ('includes/connect.php'); $echoarray = array(); $resultsql = mysql_query("SELECT * FROM clients")or die(mysql_error()); while($row = mysql_fetch_array($resultsql)){ if(empty($echoarray)){ $echoarray = array( 'id' => $row['ID'], 'name' => $row['First_Name'] . " " . $row['Last_Name'], 'price' => $row['Status'], 'number' => $row['Sex'], 'address' => $row['Phys_Street'], 'company' => $row['Agency'], 'desc' => $row['Notes'], 'age' => $row['Date_Birth'], 'title' => $row['Occupation'], 'phone' => $row['Phone'], 'email' => $row['Email'], 'zip' => $row['Phys_Zip'], 'country' => $row['Phys_City'] ); } else { array_push($echoarray, $echoarray['id'] = $row['ID'], $echoarray['name'] = $row['First_Name'] . " " . $row['Last_Name'], $echoarray['price'] = $row['Status'], $echoarray['number'] = $row['Sex'], $echoarray['address'] = $row['Phys_Street'], $echoarray['company'] = $row['Agency'], $echoarray['desc'] = $row['Notes'], $echoarray['age'] = $row['Date_Birth'], $echoarray['title'] = $row['Occupation'], $echoarray['phone'] = $row['Phone'], $echoarray['email'] = $row['Email'], $echoarray['zip'] = $row['Phys_Zip'], $echoarray['country'] = $row['Phys_City'] ); } Any Ideas? Hi, I have a question: I have a CSV file where the first row are the names of the columns. The format of the CSV file is: Name | Surname | Adress | Date of birth Robert | Miller | Athome 1| 29. Februar 1976 . . . How should I import the CSV. Thanks in advance. I am trying to store all the elements of my tree in an array.My code produces multi dimensional array, but i want it to be one dimensional. How can i get it ? Code:- Code: [Select] function tree_gather($node) //Function to calculate count { $sql = "SELECT lchild,rchild FROM tree WHERE parent = '$node'"; $execsql = mysql_query($sql); $array = mysql_fetch_array($execsql); if(!empty($array['lchild']) || !empty($array['rchild'])) { $child[] = $array['lchild']; $child[] = $array['rchild']; $child[] = tree_gather($array['lchild']); $child[] = tree_gather($array['rchild']); } return $child; } Result:- Code: [Select] Array ( [0] => 2 [1] => 3 [2] => Array ( [0] => 4 [1] => 5 [2] => Array ( [0] => 10 [1] => 11 [2] => [3] => ) [3] => Array ( [0] => 8 [1] => 9 [2] => [3] => ) ) [3] => Array ( [0] => 7 [1] => 6 [2] => Array ( [0] => 15 [1] => 14 [2] => Array ( [0] => 16 [1] => 17 [2] => [3] => ) [3] => ) [3] => Array ( [0] => 13 [1] => 12 [2] => [3] => ) ) ) Table: - I have an array which will be below. The array is being built from an XML file, the problem is I need to extrapolate data from it.
I am having trouble with looping through the array properly.
The output should be something like this:
Beth's state is 0 (Where Beth's is the name and 0 is the state)
Clint's state is 0
Array ( [0] => Array ( [did] => 216616014153767704 [known] => 1 [lock] => 0 [state] => 0 [level] => 100 [node] => 30 [port] => 0 [nodetype] => 16386 [name] => Beth's [desc] => LED [colorid] => 1 [type] => multilevel [rangemin] => 0 [rangemax] => 99 [power] => 0 [poweravg] => 0 [energy] => 0 [score] => 0 [productid] => 1 [prodbrand] => TCP [prodmodel] => LED A19 11W [prodtype] => LED [prodtypeid] => 78 [classid] => 2 [class] => [subclassid] => 1 [subclass] => [other] => ) [1] => Array ( [did] => 216616014154116936 [known] => 1 [lock] => 0 [state] => 0 [level] => 100 [node] => 30 [port] => 0 [nodetype] => 16386 [name] => Clint's [desc] => LED [colorid] => 1 [type] => multilevel [rangemin] => 0 [rangemax] => 99 [power] => 0 [poweravg] => 0 [energy] => 0 [score] => 0 [productid] => 1 [prodbrand] => TCP [prodmodel] => LED A19 11W [prodtype] => LED [prodtypeid] => 78 [classid] => 2 [class] => [subclassid] => 1 [subclass] => [other] => ) ) I have four different arrays and I want to place them into a multi dimensional array and then I want to place it into a Session variable. This is what I have below.How do I do this? when I print_r($_Session) I don't get anything just option[](2); Code: [Select] $_SESSION ['option']['green'] = array('name '=>'jeff'); $_SESSION ['option']['red'] = array('name '=>'mary'); $_SESSION ['option']['blue'] = array('name '=>'joe'); $_SESSION ['option']['brown'] = array('name '=>'ash'); The code below is showing "undefined" and "OBJECT" errors
What am I doing wrong to build this multi-dimensional array?
And why can't I paste it to this page???????????????????????
I have a pipe delimited file with this sample content: INV8004199|01/26/2012|Next door|648.00 SPT803487|01/25/2012|This and That|3360.00 INV8004193|01/25/2012|Where is it|756.00 INV8004133|01/05/2012|snowy winter|6750.00 I open the file to read it: Code: [Select] $CPfile = "sample.DEL"; $ft = fopen( $CPfile, "r"); $content1 = fread($ft, filesize($CPfile)); fclose($ft); Then I loop thru it: Code: [Select] $out = explode("\n", $content1); $total = 0; foreach($out as $var) { $tmp = explode("|", $var); for($i=0;$i<count($tmp);$i++){ echo $tmp[$i] . "<BR>"; } } What I would like to get is the total of all prices (last column) in all lines of the file. Can someone help please?. Thanks! Hello , i am trying to sort a 2d dimensional array by the first column(id) and i havent find anything till now This is my code for the 2d array: $username = $_SESSION['username']; $c = 0; $row=1; $col=1; $users_array = array(); $get_from = mysql_query("SELECT id FROM my_activity WHERE from_user='$username'"); while($fetch1 = mysql_fetch_array($get_from)){ $id[$c] = $fetch1[0]; $get_from_user = mysql_query("SELECT * FROM my_activity WHERE id='$id[$c]'"); $get_user_rows = mysql_num_rows($get_from_user); while($guser = mysql_fetch_array($get_from_user)){ $user[$c] = $guser['to_user']; $users_array[$id[$c]][$user[$c]]= $id[$c].".".$user[$c]; $c++; } } $get_to = mysql_query("SELECT * FROM my_activity WHERE to_user='$username'"); while($fetch2 = mysql_fetch_array($get_to)){ $id[$c] = $fetch2[0]; $get_to_user = mysql_query("SELECT from_user FROM my_activity WHERE id='$id[$c]'"); while($tuser = mysql_fetch_array($get_to_user)){ $user[$c] = $tuser[0]; $users_array[$id[$c]][$user[$c]]= $id[$c].".".$user[$c]; $c++; } } This is what i get if i simply loop the array to get the result: Code: [Select] Array ( [6] => Array ( [checkdate] => 6.checkdate ) [25] => Array ( [asdsadsad] => 25.asdsadsad ) [7] => Array ( [webuser] => 7.webuser ) [9] => Array ( [newuser] => 9.newuser ) [10] => Array ( [bot77un] => 10.bot77un ) ) I am trying to sort it by the ids 6,25,7,9,10 in DESC Does anyone know of a way I can natsort a multi-dimension array by a value nested in the array 2 keys deep? I.e. array( 'test1' => array( 'location' => '123 fake street', 'time' => 120 ), 'test2' => array( 'location' => '123 elm street', 'time' => 34 ), 'test3' => array( 'location' => '123 php street', 'time' => 133 ) ); // would become array( 'test2' => array( 'location' => '123 elm street', 'time' => 34 ), 'test1' => array( 'location' => '123 fake street', 'time' => 120 ), 'test3' => array( 'location' => '123 php street', 'time' => 133 ) ); thanks for any help |