These are my two methods, I need to include them in my class but am unsure how to do it since I'm not an OO programmer
function gcd($x,$y)
{
do {
$rest=$x%$y;
$x=$y;
$y=$rest;
} while($rest!==0);
return $x;
}
function testCommonality($a)
{
$keys = array_keys($a[1]);
$common = array();
foreach ($keys as $key) {
$v1 = $a[0][$key];
$v2 = $a[1][$key];
if ((gcd($v1, $v2)) != 1) $a[0]['m'] *= 1.5;
}
return $a;
}
print_r($parser->algorithm->testCommonality());
I need to include those in this class, and have them operate on the output of $parser->algorithm Help is greatly GREATLY appreciated
class CSVParser
{
public $output = NULL;
public $digits = NULL;
public function __construct($file)
{
if (!file_exists($file)) {
throw new Exception("$file does not exist");
}
$this->contents = file_get_contents($file);
$this->output = array();
$this->digits = array();
}
public function parse($separatorChar1 = ',', $separatorChar2 = ';', $enclosureChar = '"', $newlineChar = "\n")
{
$lines = explode($newlineChar, $this->contents);
foreach ($lines as $line) {
if (strlen($line) == 0) continue;
$group = array();
list($part1, $part2) = explode($separatorChar2, $line);
$group[] = array_map(array($this, "trim_value"), explode($separatorChar1, $part1), array("$enclosureChar \t"));
$group[] = array_map(array($this, "trim_value"), explode($separatorChar1, $part2), array("$enclosureChar \t"));
$this->output[] = $group;
}
}
private function trim_value($value, $chars)
{
return preg_replace("#^( |" . $chars . ")+#", '', $value);
}
public function algorithm()
{
$alpha = array(
'c' => str_split('bcdfghjklmnpqrstvwxz'),
'v' => str_split('aeiouy')
);
$i = 0;
$k = 0;
foreach ($this->output as $item) {
$cnt = 0;
$this->digits[$i] = array();
foreach ($item as $part) {
$this->digits[$i][$cnt] = array();
$new = array();
foreach ($part as $str) {
$v = count(array_intersect(str_split($str), $alpha['v']));
$c = count(array_intersect(str_split($str), $alpha['c']));
$t = strlen(str_replace(' ', '', $str));
$new = array('v' => $v, 'c' => $c, 't' => $t);
$this->digits[$i][$cnt][] = $new;
}
$cnt++;
}
$i++;
}
}
}
$parser = new CSVParser("file.txt");
$parser->parse();
print_r($parser->output);
$parser->algorithm();
print_r($parser->digits);
Thanks for the help!
I know very little of PHP, but, if I understand correctly, what you are asking appears to be straight forward enough. I would have thought somebody would have already answered this.
The following may be something like what you are after:
class CSVParser
{
public $output = NULL;
public $digits = NULL;
public function __construct($file)
{
if (!file_exists($file)) {
throw new Exception("$file does not exist");
}
$this->contents = file_get_contents($file);
$this->output = array();
$this->digits = array();
}
public function parse($separatorChar1 = ',', $separatorChar2 = ';', $enclosureChar = '"', $newlineChar = "\n")
{
$lines = explode($newlineChar, $this->contents);
foreach ($lines as $line) {
if (strlen($line) == 0) continue;
$group = array();
list($part1, $part2) = explode($separatorChar2, $line);
$group[] = array_map(array($this, "trim_value"), explode($separatorChar1, $part1), array("$enclosureChar \t"));
$group[] = array_map(array($this, "trim_value"), explode($separatorChar1, $part2), array("$enclosureChar \t"));
$this->output[] = $group;
}
}
private function trim_value($value, $chars)
{
return preg_replace("#^( |" . $chars . ")+#", '', $value);
}
public function algorithm()
{
$alpha = array(
'c' => str_split('bcdfghjklmnpqrstvwxz'),
'v' => str_split('aeiouy')
);
$i = 0;
$k = 0;
foreach ($this->output as $item) {
$cnt = 0;
$this->digits[$i] = array();
foreach ($item as $part) {
$this->digits[$i][$cnt] = array();
$new = array();
foreach ($part as $str) {
$v = count(array_intersect(str_split($str), $alpha['v']));
$c = count(array_intersect(str_split($str), $alpha['c']));
$t = strlen(str_replace(' ', '', $str));
$new = array('v' => $v, 'c' => $c, 't' => $t);
$this->digits[$i][$cnt][] = $new;
}
$cnt++;
}
$i++;
}
return $this->digits;
}
private function gcd($x,$y)
{
do {
$rest=$x%$y;
$x=$y;
$y=$rest;
} while($rest!==0);
return $x;
}
public function testCommonality($a)
{
$keys = array_keys($a[1]);
$common = array();
foreach ($keys as $key) {
$v1 = $a[0][$key];
$v2 = $a[1][$key];
if ((gcd($v1, $v2)) != 1) $a[0]['m'] *= 1.5;
}
return $a;
}
}
$parser = new CSVParser("file.txt");
$parser->parse();
print_r($parser->output);
$parser->algorithm();
print_r($parser->digits);
print_r( $parser->testCommonality( $parser->digits() ) );
`
Related
$arr['animal'][0] = 'Dog';
$arr['animal'][1] = 'Cat';
From that array basically I need to create a function with the array value parameter and then it gives me the array keys.
For example:
find_index('Cat');
Output :
The result is animal, 1
You could probably do something like
function find_index($value) {
foreach ($arr as $index => $index2) {
$exists = array_search($value, $index2);
if ($exists !== false) {
echo "The result is {$index}, {$exists}";
return true;
}
}
return false;
}
Try this:
$arr['animal'][0] = 'Dog';
$arr['animal'][1] = 'Cat';
function find_index($searchVal, $arr){
return array_search($searchVal, $arr);
}
print_r(find_index('Cat', $arr['animal']));
Consider this Array,
$arr['animal'][] = 'Dog';
$arr['animal'][] = 'Cat';
$arr['insects'][] = 'Insect1';
$arr['insects'][] = 'Insect2';
Here is Iterator Method,
$search = 'InsectSub1';
$matches = [];
$arr_array = new RecursiveArrayIterator($arr);
$arr_array_iterator = new RecursiveIteratorIterator($arr_array);
foreach($arr_array_iterator as $key => $value)
{
if($value === $search)
{
$fill = [];
$fill['category'] = $arr_array->key();
$fill['key'] = $arr_array_iterator->key();
$fill['value'] = $value;
$matches[] = $fill;
}
}
if($matches)
{
// One or more Match(es) Found
}
else
{
// Not Found
}
$arr['animal'][] = 'Dog';
$arr['animal'][] = 'Cat';
$arr['insects'][] = 'Insect1';
$arr['insects'][] = 'Insect2';
$search_for = 'Cat';
$search_result = [];
while ($part = each($arr)) {
$found = array_search($search_for, $part['value']);
if(is_int($found)) {
$fill = [ 'key1' => $part['key'], 'key2' => $found ];
$search_result[] = $fill;
}
}
echo 'Found '.count($search_result).' result(s)';
print_r($search_result);
Hi I am using serialize & unserialize functions and fwrite & fopen for text based db
<?php
ini_set('display_errors', 'on');
header('Content-Type: text/html; charset=utf-8');
$debugged = (bool) isset($_GET['debug']);
error_reporting($debugged ? E_ALL : 0);
$data_filename = "database.txt";
$admins = array(
"admin" => "admin",
"admin2" => "admin2"
);
$superadmin = "admin";
$order = "asc";
include_once "functions.php";
?>
<?php
function clean($d) {
return str_replace(array(
"\t",
"\n",
"\s",
"\r"
), "", $d);
}
function add($email, $age_id, $gender_id, $city, $prof_id, $model, $token, $os_version, $udid, $admin) {
global $data_filename;
$datax['email'] = $email;
$datax['age_id'] = $age_id;
$datax['gender_id'] = $gender_id;
$datax['city'] = $city;
$datax['prof_id'] = $prof_id;
$datax['model'] = $model;
$datax['token'] = $token;
$datax['os_version'] = $os_version;
$datax['udid'] = $udid;
$datax['admin'] = $admin;
$data = array();
$data_content = get_file_content($data_filename);
if ($data_content !== NULL)
$data = unserialize($data_content);
$entrie = serialize($datax);
$data[] = $entrie;
$data_content = serialize($data);
put_file_content($data_filename, $data_content);
return $data_content;
}
function get_file_content($filename) {
if (!file_exists($filename))
fclose(fopen($filename, "w"));
if (!file_exists($filename))
die("sie.");
$content = (filesize($filename) > 0) ? #fread(fopen($filename, "r+"), filesize($filename)) : NULL;
if ($content === false)
die("aq");
return $content;
}
if (!$data_filename) {
die("sie-31");
}
$datasey = array();
$data_content = get_file_content($data_filename);
if ($data_content !== NULL)
$datasey = #unserialize($data_content);
function put_file_content($filename, $content) {
if (file_put_contents($filename, $content, LOCK_EX)) {
return true;
} else {
usleep(250000);
put_file_content($filename, $content, LOCK_EX);
}
}
function reverse_data($data) {
$data = array_reverse($data);
foreach ($data as $key => $entrie)
$key = $entries_num - $key - 1;
return $data;
}
function del_admin_contents($who) {
global $admin, $superadmin, $data_filename;
;
$array = array();
$data_content = get_file_content($data_filename);
if ($data_content === NULL)
return;
$array = unserialize($data_content);
foreach ($array as $key => $value) {
$bok = unserialize($value);
if ($bok["admin"] == $who) {
unset($array[$key]);
}
}
$temp = array();
foreach ($array as $value)
$temp[] = $value;
$data_content = serialize($array);
put_file_content($data_filename, $data_content);
return $data_content;
}
function del_entries($select, $udid) {
global $data_filename;
$data = array();
$data_content = get_file_content($data_filename);
if ($data_content === NULL)
return;
$data = unserialize($data_content);
$data = del_id($data, $select, $udid);
$data_content = serialize($data);
put_file_content($data_filename, $data_content);
return $data_content;
}
function del_id($array, $id_array, $udid) {
global $admin, $superadmin;
foreach ($id_array as $id)
if (isset($array[$id])) {
$bok = unserialize($array[$id]);
if ($bok["admin"] == $admin || $admin == $superadmin) {
if ($bok["udid"] == $udid) {
unset($array[$id]);
}
}
}
$temp = array();
foreach ($array as $value)
$temp[] = $value;
return $temp;
}
function up_id($array, $new_array, $id) {
global $admin, $superadmin;
if (isset($array[$id])) {
$array[$id] = serialize($new_array);
}
return $array;
}
function update_id($data, $id, $new_array) {
global $data_filename;
$data = up_id($data, $new_array, $id);
$data_content = serialize($data);
put_file_content($data_filename, $data_content);
return true;
}
function emailupdate($udid, $email) {
global $data_filename;
$data = array();
$ret = false;
$data_content = get_file_content($data_filename);
if ($data_content === NULL)
return false;
$data = unserialize($data_content);
$id = 0;
foreach ($data as $d) {
$new_array = unserialize($d);
if ($new_array["udid"] == $udid) {
$new_array["email"] = $email;
update_id($data, $id, $new_array);
$ret = true;
}
$id++;
}
return $ret;
}
function alldata() {
global $datasey;
$benimdata = array();
if (count($datasey) > 0) {
foreach ($datasey as $key => $entrie) {
$gec = unserialize($entrie);
$benimdata[] = $gec;
}
return $benimdata;
} else {
return false;
}
}
function cleaner() {
global $data_filename, $max_entries;
if ($max_entries == 0)
return;
$data = array();
$data_content = get_file_content($data_filename);
if ($data_content !== NULL)
$data = unserialize($data_content);
while (count($data) >= $max_entries)
$data = clear_id($data, array(
0
));
$data_content = serialize($data);
put_file_content($data_filename, $data_content);
return true;
}
function logincheck($user, $pass) {
global $admins;
if (array_key_exists($user, $admins)) {
if ($admins[$user] == $pass) {
return true;
} else {
return false;
}
} else {
return false;
}
}
$backup = "./backup/" . date("Ymd-H:i") . ".dat";
if (!file_exists($backup)) {
$backup_data_content = get_file_content($data_filename);
file_put_contents($backup, $backup_data_content, LOCK_EX);
}
?>
As here is an example of how I add new value(s):
$data_content=add($_POST["email"],$_POST["age_id"],$_POST["gender_id"],$_POST["city_id"],$_POST["prof_id"],$_POST["model"],"N/A",$_POST["os_version"],$randomudid,$admin);
for delete :
$data_content=del_entries(array($_GET["del"]),$_GET["delete"]);
My question is when 2 admins try to enter a value at the same time it writes to database only the last value sent and deletes the old values, how can I resolve this issue?
I find theese php codes here, but codes aren't working correctly. it seems that the if(isset($words[$word])) doesn't go through as I always get an empty results array
$boggle = "fxie
amlo
ewbx
astu";
$alphabet = str_split(str_replace(array("\n", " ", "\r"), "", strtolower($boggle)));
$rows = array_map('trim', explode("\n", $boggle));
$dictionary = file("C:/dict.txt");
$prefixes = array(''=>'');
$words = array();
$regex = '/[' . implode('', $alphabet) . ']{3,}$/S';
foreach($dictionary as $k=>$value) {
$value = trim(strtolower($value));
$length = strlen($value);
if(preg_match($regex, $value)) {
for($x = 0; $x < $length; $x++) {
$letter = substr($value, 0, $x+1);
if($letter == $value) {
$words[$value] = 1;
} else {
$prefixes[$letter] = 1;
}
}
}
}
$graph = array();
$chardict = array();
$positions = array();
$c = count($rows);
for($i = 0; $i < $c; $i++) {
$l = strlen($rows[$i]);
for($j = 0; $j < $l; $j++) {
$chardict[$i.','.$j] = $rows[$i][$j];
$children = array();
$pos = array(-1,0,1);
foreach($pos as $z) {
$xCoord = $z + $i;
if($xCoord < 0 || $xCoord >= count($rows)) {
continue;
}
$len = strlen($rows[0]);
foreach($pos as $w) {
$yCoord = $j + $w;
if(($yCoord < 0 || $yCoord >= $len) || ($z == 0 && $w == 0)) {
continue;
}
$children[] = array($xCoord, $yCoord);
}
}
$graph['None'][] = array($i, $j);
$graph[$i.','.$j] = $children;
}
}
function to_word($chardict, $prefix) {
$word = array();
foreach($prefix as $v) {
$word[] = $chardict[$v[0].','.$v[1]];
}
return implode("", $word);
}
function find_words($graph, $chardict, $position, $prefix, $prefixes, &$results, $words) {
$word = to_word($chardict, $prefix);
if(!isset($prefixes[$word])) return false;
**if(isset($words[$word])) {
$results[] = $word;
}**
foreach($graph[$position] as $child) {
if(!in_array($child, $prefix)) {
$newprefix = $prefix;
$newprefix[] = $child;
find_words($graph, $chardict, $child[0].','.$child[1], $newprefix, $prefixes, $results, $words);
}
}
}
$solution = array();
find_words($graph, $chardict, 'None', array(), $prefixes, $solution);
print_r($solution);
When you call find_words() at the end, you are only passing 6 parameters
find_words($graph, $chardict, 'None', array(), $prefixes, $solution);
The variable $words, is the 7th parameter in your definition of find_words()
function find_words($graph, $chardict, $position, $prefix, $prefixes, &$results, $words) {
Hence, $words will always be empty, and isset($words[$word]) will always be false
I have list of brands and want to provide a search function with highlighting. For example, there are the following brands
Apple
Cewe Color
L'Oréal
Microsoft
McDonald's
Tom Tailor
The user then types lor in search form. I'm using the following snippet for searching
class search {
private function simplify($str) {
return str_replace(array('&',' ',',','.','?','|','\'','"'), '', iconv('UTF-8', 'ASCII//TRANSLIT', $str));
}
public function do_search($search) {
$search = self::simplify($search);
$found = array();
foreach (self::$_brands as $brand) {
if (mb_strstr(self::simplify($brand['name']), $search) !== false) $found[]= $brand;
}
return $found;
}
}
That gives me:
Cewe Color
L'Oréal
Tom Tailor
How would be a highlighting possible? Like:
Cewe Co<b>lor</b>
L'<b>Oré</b>al
Tom Tai<b>lor</b>
Btw: I know, that most things can be done with str_replace(), but that fit my needs not in all cases
$highlighted = str_replace($search, "<b>$search</b>", $brand);
would be the simplest method.
:)
Works with FedEx also ;)
$_brands = array
(
"Apple",
"Cewe Color",
"L'Oréal",
"Microsoft",
"McDonald's",
"Tom Tailor"
);
$q = 'lor';
$search = clean($q);
foreach($_brands as $key => $brand){
$brand = clean($brand);
$x = stripos($brand, $search);
if($x !== false){
$regexp = NULL;
$l = strlen($q);
for($i = 0; $i < $l; $i++){
$regexp .= mb_strtoupper($q[$i]).'.?';
}
$regexp = substr($regexp, 0, strlen($regexp) - 2);
$new = $_brands[$key];
$new = preg_replace('#('.$regexp.')#ui', '<b>$0</b>', $new);
echo $new."<br />";
}
}
function clean($string){
$string = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $string);
$string = preg_replace('#[^\w]#ui', '', $string);
return $string;
}
self::$_brands contains result from database (containing columns name, name_lower, name_translit, name_simplified)
class search {
private function translit($str) {
return iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', str_replace(array('ä', 'ü', 'ö', 'ß'), array('a', 'u', 'o', 's'), mb_strtolower($str)));
}
private function simplify($str) {
return preg_replace('/([^a-z0-9])/ui', '', self::translit($str));
}
public function do_search($simplified) {
$found = array();
foreach (self::$_brands as $brand) {
if (mb_strstr($brand['name_simplified'], $simplified) !== false) $found[]= $brand;
}
return $found;
}
private function actionDefault() {
$search = $_POST['search_fld'];
$simplified = self::simplify($search);
$result = self::do_search($simplified);
$brands = array();
foreach ($result as $brand) {
$hl_start = mb_strpos($brand['name_simplified'], $simplified);
$hl_len = mb_strlen($simplified);
$brand_len = mb_strlen($brand['name']);
$tmp = '';
$cnt_extra = 0;
$start_tag = false;
$end_tag = false;
for ($i = 0; $i < $brand_len; $i++) {
if (($i - $cnt_extra) < mb_strlen($brand['name_simplified']) && mb_substr($brand['name_translit'], $i, 1) != mb_substr($brand['name_simplified'], $i - $cnt_extra, 1)) $cnt_extra++;
if (($i - $cnt_extra) == $hl_start && !$start_tag) {
$tmp .= '<b>';
$start_tag = true;
}
$tmp .= mb_substr($brand['name'], $i, 1);
if (($i - $cnt_extra + 1) == ($hl_start + $hl_len) && !$end_tag) {
$tmp .= '</b>';
$end_tag = true;
}
}
if ($start_tag && !$end_tag) $tmp .= '</b>';
$brands[] = "" . $tmp . "";
}
echo implode(' | ', $brands);
}
}
I need to build an tree (with arrays) from given urls.
I have the following list of urls:
http://domain.com/a/a.jsp
http://domain.com/a/b/a.jsp
http://domain.com/a/b/b.jsp
http://domain.com/a/b/c.jsp
http://domain.com/a/c/1.jsp
http://domain.com/a/d/2.jsp
http://domain.com/a/d/a/2.jsp
now i need an array like this:
domain.com
a
a.jsp
b
a.jsp
b.jsp
c.jsp
c
1.jsp
d
2.jsp
a
2.jsp
How can i do this with php?
i thought mark's solution was a bit complicated so here's my take on it:
(note: when you get to the filename part of the URI, I set it as both the key and the value, wasn't sure what was expected there, the nested sample didn't give much insight.)
<?php
$urls = array(
'http://domain.com/a/a.jsp',
'http://domain.com/a/b/a.jsp',
'http://domain.com/a/b/b.jsp',
'http://domain.com/a/b/c.jsp',
'http://domain.com/a/c/1.jsp',
'http://domain.com/a/d/2.jsp',
'http://domain.com/a/d/a/2.jsp'
);
$array = array();
foreach ($urls as $url)
{
$url = str_replace('http://', '', $url);
$parts = explode('/', $url);
krsort($parts);
$line_array = null;
$part_count = count($parts);
foreach ($parts as $key => $value)
{
if ($line_array == null)
{
$line_array = array($value => $value);
}
else
{
$temp_array = $line_array;
$line_array = array($value => $temp_array);
}
}
$array = array_merge_recursive($array, $line_array);
}
print_r($array);
?>
$urlArray = array( 'http://domain.com/a/a.jsp',
'http://domain.com/a/b/a.jsp',
'http://domain.com/a/b/b.jsp',
'http://domain.com/a/b/c.jsp',
'http://domain.com/a/c/1.jsp',
'http://domain.com/a/d/2.jsp',
'http://domain.com/a/d/a/2.jsp'
);
function testMapping($tree,$level,$value) {
foreach($tree['value'] as $k => $val) {
if (($val == $value) && ($tree['level'][$k] == $level)) {
return true;
}
}
return false;
}
$tree = array();
$i = 0;
foreach($urlArray as $url) {
$parsed = parse_url($url);
if ((!isset($tree['value'])) || (!in_array($parsed['host'],$tree['value']))) {
$tree['value'][$i] = $parsed['host'];
$tree['level'][$i++] = 0;
}
$path = explode('/',$parsed['path']);
array_shift($path);
$level = 1;
foreach($path as $k => $node) {
if (!testMapping($tree,$k+1,$node)) {
$tree['value'][$i] = $node;
$tree['level'][$i++] = $level;
}
$level++;
}
}
echo '<pre>';
for ($i = 0; $i < count($tree['value']); $i++) {
echo str_repeat(' ',$tree['level'][$i]*2);
echo $tree['value'][$i];
echo '<br />';
}
echo '</pre>';