Remove Duplicated Entries From an Array - php

For removing the duplicated entries I know I have to use array_unique() but unfortunately by using this I got unexpected result(s). My PHP code is this:
$query = $db->query("
SELECT sid,father_contact,residential_contact
FROM ".TABLE_PREFIX."student_list
{$where_clause}
ORDER BY sid ASC");
while ($s = $db->fetch_array($query))
{
if (!empty($s['father_contact']))
{
$father_contact = $s['father_contact'].', ';
}
else
{
$father_contact = '';
}
if (!empty($s['residential_contact']))
{
$residential_contact = $s['residential_contact'].', ';
}
else
{
$residential_contact = '';
}
$phone_nums_bit .= $father_contact.$residential_contact;
}
This grabs all phone numbers from the database tables and print the result like this:
03334523675, 03124237009, 03134237002, 03124237009, 03217832173, 03134237002, 3134237002, 03124237009,
Notice that few numbers like 03134237002 is repeating thrice. I want to remove duplicate entries from this result. Please help me to sort it out. Thanks.

You can try to do it via array structures. Just to give you an idea:
$phones = [];
while ($s = $db->fetch_array($query))
{
if (!empty($s['father_contact']))
{
$phones[] = $s['father_contact'];
}
if (!empty($s['residential_contact']))
{
$phones[] = $s['residential_contact'];
}
}
$phones = array_unique($phones);
// and then combine into string
$phone_nums_bit = implode(', ', $phones);

Related

PHP sql statement where clause to multiple array values

How do i use where clause for array if value[3] has multiple data stored
$fsql="select * from Error where RptDatime = 201706091000 and partnumber like ('$value[3]')";
$getResults = $conn->prepare($fsql);
$getResults->execute();
$results = $getResults->fetchAll(PDO::FETCH_BOTH);
foreach($results as $row)
{
$mac = $row['Machine'];
$id = $row['Id'];
echo 'ID:'.$id.'Machine Number :'.$mac;
}
You can use regex function instead of like. Below is the sample code for you.
$partnumner = [];
foreach($value[3] as $v)
{
$partnumber[] = "*.".$v.".*";
}
$fsql="select * from Error where RptDatime = 201706091000 and partnumber REGEXP '".implode("|",$partnumber)."'";
If you still wish to use like, you can follow the answer here
I assume that you have array of numbers so, first you should validate for expected data and then to implode it into comma separated string.
if(!isset($value[3])){
return false;
}
if(!is_array($value[3])){
return false;
}
foreach($value[3] as $number){
if(!is_numeric($number)){
return false;
}
}
$numbers = implode(",",$value[3]);
$fsql=sprintf("select * from Error where RptDatime = 201706091000 and partnumber in (%s)",$numbers);
$getResults = $conn->prepare($fsql);
$getResults->execute();
$results = $getResults->fetchAll(PDO::FETCH_BOTH);
foreach($results as $row)
{
$mac = $row['Machine'];
$id = $row['Id'];
echo 'ID:'.$id.'Machine Number :'.$mac;
}

get unique tags and number of occurrences from mysql using php

there is a "post" table in mysql and column "tags".
Tags' value is like apple,orange,peach,etc.
I'm trying to get all the tags and assign tag & number of occurances to array using php. Here is what I am trying to do.
$recmostusedtagscol = array();
$recmostusedtagsq = mysqli_query($connecDB,"select tags from post limit 5");
while($recmostusedtagsr = mysqli_fetch_array($recmostusedtagsq)){
$tagsarray = explode(',', $recmostusedtagsr['tags']);
foreach ($tagsarray as $tag) {
if(in_array($tag,$recmostusedtagscol)){
$recmostusedtagscol[$tag][]++;
}
else {
$recmostusedtagscol .= [$tag => 1];
}
}
}
print_r($recmostusedtagscol);
UPDATED:
this one is close. It is listing uniqe values, but it is not adding plus 1 to the array value.
$recmostusedtagscol = array();
$recmostusedtagsq = mysqli_query($connecDB,"select tags from post");
while($recmostusedtagsr = mysqli_fetch_array($recmostusedtagsq)){
$tagsarray = explode(',', $recmostusedtagsr['tags']);
foreach ($tagsarray as $tag) {
if(in_array($tag,$recmostusedtagscol)){
$recmostusedtagscol[$tag]++;
}
else {
$recmostusedtagscol[$tag]=1;
}
}
}
print_r($recmostusedtagscol);
it seems in_array() is not working.... maybe....
Based on the comments, here is the working one.
$recmostusedtagscol = array();
$recmostusedtagsq = mysqli_query($connecDB,"select tags from post");
while($recmostusedtagsr = mysqli_fetch_array($recmostusedtagsq)){
$tagsarray = explode(',', $recmostusedtagsr['tags']);
foreach ($tagsarray as $tag) {
if(isset($recmostusedtagscol[$tag])){
$recmostusedtagscol[$tag]++;
}
else {
$recmostusedtagscol[$tag]=1;
}
}
}
Thanks to #Mark Baker and #arkascha

Add comma after value in Mysql PHP

I use below code,
$i = 0; $comma = NULL;
foreach($messages->get_logged_agents_dep(60) as $val_dep)
{
echo $department_id = $val_dep['department_id'].$comma;
}
I want to put comma (,) end of department_id (as I mentioned in $comma variable)
but last value should not put comma(,), because of I want to put above values in to SELECT * FROM tb_name WHERE IN (1,2,3) like this,
please help me to resolve this.
respect to your responds.
Thanks!
Try this :-
foreach($messages->get_logged_agents_dep(60) as $val_dep)
{
$department_id[] = $val_dep['department_id'];
}
echo $department_val = implode(",",$department_id);
You can also use rtrim()
$department_id = '';
foreach($messages->get_logged_agents_dep(60) as $val_dep) {
$department_id .= $val_dep['department_id'].',';
}
rtrim($department_id,','); // to trim last comma
Change your code to add the comma on the additional member of the sequence, not with.
$i = 0;
$comma = ',';
foreach(...)
{
echo ($i++>0)? $comma:'';
echo $department_id = $val_dep['department_id'];
}
Use implode(). See http://php.net/manual/en/function.implode.php
$i = 0; $arrIds = array();
foreach($messages->get_logged_agents_dep(60) as $val_dep)
{
$arrIds[] = $val_dep['department_id'];
}
echo implode(',', $arrIds);

Pulling NHL Standings from XML Table with PHP

I'm working on a project in which I pull various statistics about the NHL and inserting them into an SQL table. Presently, I'm working on the scraping phase, and have found an XML parser that I've implemented, but I cannot for the life of me figure out how to pull information from it. The table can be found here -> http://www.tsn.ca/datafiles/XML/NHL/standings.xml.
The parser supposedly generates a multi-dimmensional array, and I'm simply trying to pull all the stats from the "info-teams" section, but I have no idea how to pull that information from the array. How would I go about pulling the number of wins Montreal has? (Solely as an example for the rest of the stats)
This is what the page currently looks like -> http://mattegener.me/school/standings.php
here's the code:
<?php
$strYourXML = "http://www.tsn.ca/datafiles/XML/NHL/standings.xml";
$fh = fopen($strYourXML, 'r');
$dummy = fgets($fh);
$contents = '';
while ($line = fgets($fh)) $contents.=$line;
fclose($fh);
$objXML = new xml2Array();
$arrOutput = $objXML->parse($contents);
print_r($arrOutput[0]); //This print outs the array.
class xml2Array {
var $arrOutput = array();
var $resParser;
var $strXmlData;
function parse($strInputXML) {
$this->resParser = xml_parser_create ();
xml_set_object($this->resParser,$this);
xml_set_element_handler($this->resParser, "tagOpen", "tagClosed");
xml_set_character_data_handler($this->resParser, "tagData");
$this->strXmlData = xml_parse($this->resParser,$strInputXML );
if(!$this->strXmlData) {
die(sprintf("XML error: %s at line %d",
xml_error_string(xml_get_error_code($this->resParser)),
xml_get_current_line_number($this->resParser)));
}
xml_parser_free($this->resParser);
return $this->arrOutput;
}
function tagOpen($parser, $name, $attrs) {
$tag=array("name"=>$name,"attrs"=>$attrs);
array_push($this->arrOutput,$tag);
}
function tagData($parser, $tagData) {
if(trim($tagData)) {
if(isset($this->arrOutput[count($this->arrOutput)-1]['tagData'])) {
$this->arrOutput[count($this->arrOutput)-1]['tagData'] .= $tagData;
}
else {
$this->arrOutput[count($this->arrOutput)-1]['tagData'] = $tagData;
}
}
}
function tagClosed($parser, $name) {
$this->arrOutput[count($this->arrOutput)-2]['children'][] = $this->arrOutput[count($this- >arrOutput)-1];
array_pop($this->arrOutput);
}
}
?>
add this search function to your class and play with this code
$objXML = new xml2Array();
$arrOutput = $objXML->parse($contents);
// first param is always 0
// second is 'children' unless you need info like last updated date
// third is which statistics category you want for example
// 6 => the array you want that has wins and losses
print_r($arrOutput[0]['children'][6]);
//using the search function if key NAME is Montreal in the whole array
//result will be montreals array
$search_result = $objXML->search($arrOutput, 'NAME', 'Montreal');
//first param is always 0
//second is key name
echo $search_result[0]['WINS'];
function search($array, $key, $value)
{
$results = array();
if (is_array($array))
{
if (isset($array[$key]) && $array[$key] == $value)
$results[] = $array;
foreach ($array as $subarray)
$results = array_merge($results, $this->search($subarray, $key, $value));
}
return $results;
}
Beware
this search function is case sensitive it needs modifications like match to
a percentage the key or value changing capital M in montreal to lowercase will be empty
Here is the code I sent you working in action. Pulling the data from the same link you are using also
http://sjsharktank.com/standings.php
I have actually used the same exact XML file for my own school project. I used DOM Document. The foreach loop would get the value of each attribute of team-standing and store the values. The code will clear the contents of the table standings and then re-insert the data. I guess you could do an update statement, but this assumes you never did any data entry into the table.
try {
$db = new PDO('sqlite:../../SharksDB/SharksDB');
$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
} catch (Exception $e) {
echo "Error: Could not connect to database. Please try again later.";
exit;
}
$query = "DELETE FROM standings";
$result = $db->query($query);
$xmlDoc = new DOMDocument();
$xmlDoc->load('http://www.tsn.ca/datafiles/XML/NHL/standings.xml');
$searchNode = $xmlDoc->getElementsByTagName( "team-standing" );
foreach ($searchNode as $searchNode) {
$teamID = $searchNode->getAttribute('id');
$name = $searchNode->getAttribute('name');
$wins = $searchNode->getAttribute('wins');
$losses = $searchNode->getAttribute('losses');
$ot = $searchNode->getAttribute('overtime');
$points = $searchNode->getAttribute('points');
$goalsFor = $searchNode->getAttribute('goalsFor');
$goalsAgainst = $searchNode->getAttribute('goalsAgainst');
$confID = $searchNode->getAttribute('conf-id');
$divID = $searchNode->getAttribute('division-id');
$query = "INSERT INTO standings ('teamid','confid','divid','name','wins','losses','otl','pts','gf','ga')
VALUES ('$teamID','$confID','$divID','$name','$wins','$losses','$ot','$points','$goalsFor','$goalsAgainst')";
$result= $db->query($query);
}

jQuery tag suggestion

I'm try include this plugin on my site, it's working fine but I am having some problems with PHP.
When I write the PHP like this:
$default_tags = 'Avanture, Giorgio, Armani, Depeche, Mode, Pevanje, Francuska, usluživanje, Pravo, Menadžer, prodaje, Advokat';
if (!#$_SESSION['existing_tags']) {
$_SESSION['existing_tags'] = $default_tags;
}
$existing_tags = $_SESSION['existing_tags'];
$tags = split(' ', $default_tags);
if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && #$_GET['tag']) {
$match = array();
foreach ($tags as $tag) {
if (stripos($tag, $_GET['tag']) === 0) {
$match[] = $tag;
}
}
echo json_encode($match);
}
exit;
}
it works fine, but when I try to get a result from the database I have problems.
I have tried:
$query = mysql_query("SELECT * FROM tags");
while($row = mysql_fetch_array($query)) {
$default_tags = ''.$row['keyz'].', ';
if (!#$_SESSION['existing_tags']) {
$_SESSION['existing_tags'] = $default_tags;
}
$existing_tags = $_SESSION['existing_tags'];
$tags = split(' ', $default_tags);
if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && #$_GET['tag']) {
$match = array();
foreach ($tags as $tag) {
if (stripos($tag, $_GET['tag']) === 0) {
$match[] = $tag;
}
}
echo json_encode($match);
}
exit;
}
And this method is not working for me. Also, here is a screenshot from my database table tags. What is wrong with the above code?
Your problem is you keep overriding $default_tags variable over and over again.
At the end of your while loop, all you have is your last row with a comma at the end.
Basically you're not storing anything but the last row in that variable.
If you do the following you would have something similar what you're trying to do:
$default_tags_arr = array();
while($row = mysql_fetch_array($query)) {
array_push($default_tags_arr, $row["keyz"]);
}
$default_tags = join(", ",$default_tags_arr);
You should describe exactly what the problem is. Do you get an error message?
One thing I'm seeing that seems wrong to me is the fetch from the database:
while($row = mysql_fetch_array($query)) {
$default_tags = ''.$row['keyz'].', ';
For every row you are overriding $default_tags completely. I think maybe you wanted to say:
while($row = mysql_fetch_array($query)) //where does the curly brace closes in the original code?
$default_tags .= ''.$row['keyz'].', '; //notice the . before =
to concatenate the tags.
Aside from this I'm having trouble understanding the code:
$existing_tags = $_SESSION['existing_tags'];
$tags = split(' ', $default_tags);
Here you are assigning the variable $existing_tags which you don't use later in the code. Did you want to use it in the next line instead of $default_tags? What is the code supposed to do exactly?

Categories