Extracting and grouping database data to an array - php

I have a database field called "servers"
This field has a link in each row, this field content:
> http://www.rapidshare.com/download1
> http://www.rapidshare.com/download2
> http://www.rapidshare.com/download3
> http://www.megaupload.com/download1
> http://www.megaupload.com/download2
> http://www.megaupload.com/download3
> http://www.fileserve.com/download1
> http://www.fileserve.com/download2
> http://www.fileserve.com/download3
I want to create an array with all the server names, and create more array with links inside.
That's how it should be:
$servers = array(
'rapidshare' => array(
'link1' => 'http://www.rapidshare.com/download1',
'link2' => 'http://www.rapidshare.com/download2',
'link3' => 'http://www.rapidshare.com/download3'),
'megaupload' => array(
'link1' => 'http://www.megaupload.com/download1',
'link2' => 'http://www.megaupload.com/download2',
'link3' => 'http://www.megaupload.com/download3'),
'fileserve' => array(
'link1' => 'http://www.megaupload.com/download1',
'link2' => 'http://www.megaupload.com/download2',
'link3' => 'http://www.megaupload.com/download3')
);

This will do the trick: (make sure that domain is actually showing up in $domain variable though because it might be $matches[1]... I can't remember)
$newStructure = array();
foreach($links as $link) {
preg_match("/www\.([^\.])\.com/",$link,$matches);
$domain = $matches[0];
$currentLength = count($newStructure[$domain]);
if($currentLength) {
$newStructure[$domain]['link'.($currentLength+1)] = $link;
} else {
$newStructure[$domain] = array('link1'=>$link);
}
}

$server = array(
'http://www.rapidshare.com/download1',
'http://www.rapidshare.com/download2',
'http://www.rapidshare.com/download3',
'http://www.megaupload.com/download1',
'http://www.megaupload.com/download2',
'http://www.megaupload.com/download3',
'http://www.fileserve.com/download1',
'http://www.fileserve.com/download2',
'http://www.fileserve.com/download3'
);
$match = array();
$myarray = array();
foreach($server as $v) {
// grab server name
preg_match('/\.(.+)\./', $v, $match);
$serverName = $match[1];
// initialize new array if its the first link of that particular server
if (!isset($myarray[$serverName])) {
$myarray[$serverName] = array();
}
// count server array to check how many links are there, and make next link key
$linkKey = 'link' . (count($myarray[$serverName]) + 1);
// store value
$myarray[$serverName][$linkKey] = $v;
}
print_r($myarray);
Hey maybe this will help you. But i dont see the purpose of those names of the keys (link1,link2 etc..). This wont work on pagination thou.

Related

Want to Filter an array according to value

I have a variable $a='san-serif' and an array Font_list[] now I want only the arrays whose category is 'san-serif' will be filtered. I tried a lot of codes nothing seems working here is my code:-
public function filterFont() {
$a = $_POST['key'];
$url = "https://www.googleapis.com/webfonts/v1/webfonts?key=''";
$result = json_decode(file_get_contents( $url ));
$font_list = "";
foreach ( $result->items as $font )
{
$font_list[] = [
'font_name' => $font->family,
'category' => $font->category,
'variants' => implode(', ', $font->variants),
// subsets
// version
// files
];
}
$filter = filter($font_list);
print_r(array_filter($font_list, $filter));
}
Please help me :-(
What i understood according to that you want something like below:-
<?php
$a='san-serif'; // category you want to search
$font_list=Array('0'=>Array('font_name' => "sans-sherif",'category' => "san-serif"),'1'=>Array('font_name' => "times-new-roman",'category' => "san-serif"),'2'=>Array('font_name' => "sans-sherif",'category' => "roman"));
// your original array seems something like above i mentioned
echo "<pre/>";print_r($font_list); // print original array
$filtered_data = array(); // create new array
foreach($font_list as $key=>$value){ // iterate through original array
if($value['category'] == $a){ // if array category name is equal to serach category name
$filtered_data[$key] = $value; // assign that array to newly created array
}
}
echo "<pre/>";print_r($filtered_data); // print out new array
Output:- https://eval.in/597605

How to compute tf-idf from multiple text files in php?

I'm successfully computing tf-idf from an array. Now I want that tf-idf should be computed from multiple text files as I have multiple text files in my directory. Can anyone please modify this code for multiple text files so that first all the files in the directory should read and then on the basis of these files contents tf-idf computed.. Below is my code thanks...
$collection = array(
1 => 'this string is a short string but a good string',
2 => 'this one isn\'t quite like the rest but is here',
3 => 'this is a different short string that\' not as short'
);
$dictionary = array();
$docCount = array();
foreach($collection as $docID => $doc) {
$terms = explode(' ', $doc);
$docCount[$docID] = count($terms);
foreach($terms as $term) {
if(!isset($dictionary[$term])) {
$dictionary[$term] = array('df' => 0, 'postings' => array());
}
if(!isset($dictionary[$term]['postings'][$docID])) {
$dictionary[$term]['df']++;
$dictionary[$term]['postings'][$docID] = array('tf' => 0);
}
$dictionary[$term]['postings'][$docID]['tf']++;
}
}
$temp = ('docCount' => $docCount, 'dictionary' => $dictionary);
Computing tf-idf
$index = $temp;
$docCount = count($index['docCount']);
$entry = $index['dictionary'][$term];
foreach($entry['postings'] as $docID => $postings) {
echo "Document $docID and term $term give TFIDF: " .
($postings['tf'] * log($docCount / $entry['df'], 2));
echo "\n";
}
Have a look at this answer: Reading all file contents from a directory - php
There you find the information how to read all the file contents from a directory.
With this information you should be able to modify your code by yourselve to get it work like expected.

PHP Add array and loop to code

I have a class which is working fine but I need to do multiple results.
Here is the current code:
$url = 'http://mydomain.com';
$keyword = 'somekeyword';
$RankChecker=new RankChecker(1,5);
$result=$RankChecker->find($url,$keyword);
if ($result!==false) {
echo "Your website is found at page number ".$result["page"].".";
}
What is the best way to get it to read multiple url's / keyword's ?
Put the URLs and keywords into an array and loop through it:
$urls = array(
'http://mydomain.com' => 'somekeyword',
'http://myotherdomain.com' => 'someotherkeyword'
);
$RankChecker=new RankChecker(1,5);
foreach($urls as $url => $keyword) {
$result=$RankChecker->find($url,$keyword);
if ($result!==false) {
echo "Website " . $url . " is found at page number ".$result["page"].".";
}
}
Using an array :
<?php
$websites[1] = array('url' => 'http://mydomain.com', 'keyword' => 'somekeyword');
$websites[2] = array('url' => 'http://mydomain2.com', 'keyword' => 'somekeyword2');
$websites[3] = array('url' => 'http://mydomain3.com', 'keyword' => 'somekeyword3');
// etc...
foreach ($websites as $val)
{
$RankChecker=new RankChecker(1,5);
$result=$RankChecker->find($val['url'], $val['keyword']);
if ($result!==false) {
echo "Your website is found at page number ".$result["page"].".";
}
}

Drupal PHP serialize and unserialize

In Drupal, I first serialized emails that appear in the body of private messages and stored them is MySQL like this:
function prvtmsg_list($body) {
$notify = array();
if (isset($body->emails)) {
$notify['mid'] = $body->mid;
$notify['emails'] = serialize($body->emails);
}
if (isset($body->vulgar_words) {
$notify['mid'] = $body->mid;
$notify['vulgar_words'] = serialize($message->vulgar_words);
}
if (isset($notify['mid'])) {
drupal_write_record('prvtmsg_notify', $notify);
}
}
When I later try to retrieve them, email userialization fails, I retrieve them like this:
function prvtmsg_list_notify() {
// Select fields from prvtmsg_notify and Drupal pm_message tables
$query = db_select('prvtmsg_notify', 'n');
$query->leftJoin('pm_message', 'm', 'n.mid = m.mid');
$query->fields('n', array('mid', 'emails', 'vulgar_words'));
$query->fields('m', array('mid', 'author', 'subject', 'body', 'timestamp'));
orderBy('timestamp', 'DESC');
$query = $query->extend('PagerDefault')->limit(20);
$result = $query->execute()->fetchAll();
$rows = array();
foreach ($result as $notify) {
$rows[] = array(
$notify->author,
$notify->subject,
implode(', ', unserialize($notify->emails)),
implode(', ', unserialize($notify->vulgar_words)),
);
}
$build = array();
$build['table'] = array(
'#theme' => 'table',
'#header' => array(
t('Author'),
t('Message subject'),
t('Emails captured'),
t('Vulgar Words Captured'),
),
'#rows' => $rows,
);
$build['pager']['#theme'] = 'pager';
return $build;
}
Maybe the way I serialized the emails is wrong? because:
dpm(unserialize($notify->emails);
gives Array, Array, Array - which means:
Array(
[0] => Array() [1] => Array() [2] => Array() [3] => Array()
)
Surprisingly, the unserialized vulgar words are showing okay! I'm not sure is it possible to serialize the emails like this:
$notify['emails'] = serialize (array($body->emails));
I faced the exact situation in the past where unserialization did not work for me, there is something not clear to me and I need to learn it. Could anyone confirm or tell me what's wrong?
N.B. The above code is from memory and may not be accurate as I currently don't have access to it.
if i am reading this correctly you are writing an array into a db
drupal_write_record('prvtmsg_notify', $notify);
should be:
drupal_write_record('prvtmsg_notify', serialize($notify));
you will most likely no longer need
$notify['emails'] = serialize($body->emails);
and can instead write:
$notify['emails'] = $body->emails;
after retrieving it from the db you can unserialize the array and iterate over it ex:
$array = unserialize(someFunctionToGetPrvtmsg_notifyFromTheDb());
//the array should be the same as the one you serialized

PHP - Help building a multi dimensional array

I would like to know how to get the values into this array. Can someone please help?
Each box whether it is the in or outbox should only be listed once and then have multiple ids associated with them. I need to be able to tell which id came from what box. The ids that are in the array are only samples.
$arr =
array(
'Inbox'=> array('id' => array(8, 9, 15)),
'Outbox'=> array('id' => array(8, 9, 15))
);
Thanks
$inbox = $db->Query("SELECT * FROM mail_inbox");
$outbox = $db->Query("SELECT * FROM mail_outbox");
foreach($inbox as $key => $array)
{
$output['Inbox']]['id'][] = $array['msg_seq'];
}
foreach($outbox as $key => $array)
{
$output['Outbox']]['id'][] = $array['msg_seq'];
}
print_r($output);
This will give me the db fields from the inbox but I have no idea how to get the outbox in there as well. I also get undefined index for ['Box']
Now that I know what you are saying, to input stuff, do something like this to input it into the array:
$ID = 9;
$box = "Inbox";
$arr[$box]['id'][] = $ID;
or
$IDs = array(9,5,13);
$box = "Inbox";
$array = array($box => $IDs);
or if you were getting it from a Database
$dbarray[0] = array('ID' => 9,
'Box' => 'Outbox');
foreach($dbarray as $key => $array)
{
$output[$array['Box']]['ids'][] = $array['ID'];
}
Multi deminsional arrays
The key or index is the first bracket
$array[key]="foo"
is the same as
$array = array('key' => 'foo');
if there is a second bracket, it of the array inside the value part of an array. IE
$array['key']['key2'] = "bar";
is the same as
$array = array('key' => array('key2' => 'bar'));
Basically, multideminsional arrays are just arrays inside of arrays.
foreach($arr as $box => $array)
{
echo $box;
// $box = The Box
foreach($array['ids'] as $ID)
{
echo $ID . ",";
// $ID = The ID
}
echo "<br>";
}
Sample:
Outbox 9,13,15,
Inbox 9,13,15,
This goes through each box, echos the box name, and each ID inside of the box, and echos the ID.
To access only one box
foreach($arr['Inbox'] as $ID)
{
echo $ID . ",";
}
Sample Output:
9,13,15,

Categories