each line of The file $wordFile [which is over hundreds of lines],consists of a word + 'space' + decimal number + '\n'.
I need to extract the number and word from the file and add them to the $indivFreq array. But am getting error
Notice: Undefined offset: 1 in /.....
This is my code:
$wordFile = file_get_contents("wordFile.txt");
$termArr = explode("\n", $wordFile);
$wordFile2 = file_get_contents("wordFile2.txt");
$termArr2 = explode("\n", $wordFile2);
$cityFreqsArr = array($termArr, $termArr2);
$twoTerms = array();
$decimalScore = number_format("0", 8);
$indivFreqs = array("", $decimalScore);
$twoDimFreqArr = [[]];
for($i=0; $i<count($termArr); $i++){
for($i2=0; $i2 < count($cityFreqsArr[$i]); $i2++){
$currentTerm = $cityFreqsArr[$i][$i2];
$currentTerm = trim($cityFreqsArr[$i][$i2]);
$twoTerms = explode(' ', $currentTerm); //separating each string of term and its frequency into the 2 parts
$indivFreqs[0] = $twoTerms[0];
$indivFreqs[1] = $twoTerms[1]; //**error is here
$twoDimFreqArr[$i][$i2] = $indivFreqs; //for each city and each term there is an array with the term and its frequency
//i.e.,
}
}
I tried printing out the contents of $twoTerms after the explode and am getting arrays with index 0 => word and index 1 => number, Which is why I don't understand why php won't see that it has an index of 1 also?
You've defined $cityFreqsArr as a 2-dimensional array with number of rows equal to files being read(which for this particular example is 2. first row(with $index=0) is holding $wordFile.txt/$termArr's data. And second row for the second one.
Now for storing data for each city, each term & their respective term & frequency you should first traverse $cityFreqsArr by its rows (as files) & then second level $index (as content of each file). So, I updated first & second for's conditions regarding this.
$wordFile = file_get_contents("wordFile.txt");
$termArr = explode("\n", $wordFile);
$wordFile2 = file_get_contents("wordFile2.txt");
$termArr2 = explode("\n", $wordFile2);
$cityFreqsArr = array($termArr, $termArr2);
$twoTerms = array();
$decimalScore = number_format("0", 8);
$indivFreqs = array("", $decimalScore);
$twoDimFreqArr = [[]];
for ($i = 0; $i < count($cityFreqsArr); $i++) { //Traversing file by file
for ($i2 = 0; $i2 < count($cityFreqsArr[$i]); $i2++) { //Traversing in each file
$twoTerms = explode(' ', trim($cityFreqsArr[$i][$i2]));
$indivFreqs[] = $twoTerms[0];
$indivFreqs[] = $twoTerms[1];
$twoDimFreqArr[$i][$i2] = $indivFreqs;
}
}
// Test it:
echo '<pre>';
print_r($twoDimFreqArr);
echo '</pre>';
Related
I want to merge cells dynamically based on count using PHPEXCEl.
For example:
if $count = 2;
I want to merge two cells as given below,
$objPHPExcel->getActiveSheet()->mergeCells('A1:B1');
similarly, if $count = 4;
$objPHPExcel->getActiveSheet()->mergeCells('C1:F1');
similarly, if $count = 5;
$objPHPExcel->getActiveSheet()->mergeCells('G1:K1');
I want to get this logic in a loop.
I tried the below logic, which doesn't work
$count = ew_Execute("SELECT COUNT(*) FROM ems_defects_codes WHERE DEF_CODE = '$def_code'");
$start_letter = A;
$rowno = 1;
for ($i = 0; $i < $count ; $i++) {
$objPHPExcel->getActiveSheet()->mergeCells($start_letter.$rowno.':'.$i.$rowno);
}
Any help will be much appreciated.Thanks..!!
You need to get column range string value for the inputs - start_letter, row_number and count. Once the column range is available, same can be used in the PHPExcel mergeCells function. Here is example code to get column range:
function getColRange($start_letter, $row_number, $count) {
$alphabets = range('A', 'Z');
$start_idx = array_search(
$start_letter,
$alphabets
);
return sprintf(
"%s%s:%s%s",
$start_letter,
$row_number,
$alphabets[$start_idx + $count],
$row_number
);
}
print getColRange('A', 1, 2) . PHP_EOL;
print getColRange('C', 1, 4) . PHP_EOL;
print getColRange('G', 1, 4) . PHP_EOL;
Output
A1:C1
C1:G1
G1:K1
Further you can use this new function with your code to do actual merge. You can choose to call this function or in a loop.
$sheet = $objPHPExcel->getActiveSheet();
$sheet->mergeCells(
getColRange(
$start_letter,
$row_number,
$count
)
);
The problem is that your $i inside of your loop is always going to be an integer; you need to convert that integer to the corresponding index of the alphabet, by creating an alphabetic array. This can be done with a simple range('A', 'Z').
You also need to wrap the A in $start_letter in apostrophes (as 'A'), and now that the range has been created, you can simply use the index of the alphabet for that:$start_letter = 0 (later becoming 'A' with $alphabet[$start_letter]).
Then you'll need to add the starting letter to the count for in order to get the ending cell in mergeCells(). Your starting cell now becomes $alphabet[$start_letter] . $rowno, and your ending cell now becomes ($alphabet[$start_letter] + $alphabet[$i]) . $rowno.
This can be seen in the following:
$count = ew_Execute("SELECT COUNT(*) FROM ems_defects_codes WHERE DEF_CODE = '$def_code'");
$alphabet = range('A', 'Z');
$start_letter = 0;
$rowno = 1;
for ($i = 0; $i < $count; $i++) {
$objPHPExcel->getActiveSheet()->mergeCells($alphabet[$start_letter] . $rowno . ':' . ($alphabet[$start_letter] + $alphabet[$i]) . $rowno);
}
I have a .lst(playlist) file with around 1800 lines of data. Each line contains a URL to an audio file that is being played on my radio station.
The thing is I need to add URLs to some Advertisements after every 'n' number of lines in that file.
There are 10 URLs of advertisements from which 1 URL needs to be added after every 5 lines.
Example: URLs of Advertisements are in this format: file1.mp3, file2.mp3 ... file10.mp3
They will be added like this: file1.mp3 on line 5, file2.mp3 on line 10, file3.mp3 on line 15 and so on. After file10.mp3 has been inserted, it will again start from file1.mp3. I hope you understand.
So far I have managed to cook up the following code, but it only takes up one string to be added and have to manually tell the line number on which the string will be added. Unable to figure out the looping logic to do the aforementioned work.
$url = "/home/station/content/file1.mp3";
$line_number = 5; //add above URL on line number 5
$contents = file('playlist.lst', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
if($line_number > sizeof($contents)) {
$line_number = sizeof($contents) + 1;
}
array_splice($contents, $line_number-1, 0, array($url));
$contents = implode("\n", $contents);
file_put_contents('playlist.lst', $contents);
How can I achieve this ?
You can use array_chunk to split your array into $line_number. Then, use array_map() to add your advertisements to each group. Finally, you could reduce to a linear array. You can format the $url using sprintf().
$url = "/home/station/content/file%d.mp3"; // use %d to use using sprintf()
$line_number = 5; //add above URL on line number 5
$counter = 1;
$contents = file('playlist.lst', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
// split in group of $line_number
$groups = array_chunk($contents, $line_number);
// for each group:
$groups = array_map(function($arr) use ($url, &$counter) { // pass $counter as reference
// format the link
$adv = sprintf($url, $counter++) ;
// restart to 1 if greater than 10
if ($counter > 10) $counter = 1;
// append to group
$arr[] = $adv;
return $arr ;
},$groups);
// transform to linear array
$contents = array_reduce($groups, 'array_merge', array());
// save new file
file_put_contents('playlist.lst', implode("\n", $contents));
You could do it this way, with a simple loop:
//changing it to a "model" string, we are going to add the correct file number later
$url = "/home/station/content/file";
$contents = file('playlist.lst', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$count = 0;
$AddCount = 1;
//Loop until there is nothing left in our radio list
while ($count < sizeof($contents)) {
//if we have a multiple of 5, we are inserting an ad
if (($count % 5) == 0) {
// to know wich ad to add we use our AddCounter
$tmp = $url . strval($AddCount) . ".mp3";
//As suggested by Justinas, don't forget that each time you had a line you need to also increase the index for the next one using $count%5 to know how many lines you already added
array_splice($contents, $count - 1 + ($count % 5) , 0, array($tmp));
$AddCount += 1;
if ($AddCount > 10)
$AddCount = 1;
}
$count += 1;
}
$contents = implode("\n", $contents);
file_put_contents('playlist.lst', $contents);
This way, you don't even have to handle the advertisements file selection yourself as long as they are all formated like you said.
You should do a loop in such way.
$line_number = 5;
$line_count = 0;
for($i=0; $i < sizeof($contents); $i++)
{
$line_count = $line_count +1; // start with Line 1 that +1
if($line_count == $line_number)
{
// do your magic code of adding a line
$line_count = 0; // refresh counting from the beginning
}
}
You don't need to handle each line in the file one at a time.
Leave the file contents as its original string, inject placeholders with regex, then replace those placeholders with your ad array strings.
Code: (Basic Demo)
$filename = 'playlist.lst';
file_put_contents(
$filename,
vsprintf(
preg_replace(
'/(?:.+(\R)){5}\K/', // match (and forget) 5 lines, capture the newline character
'%s\1', // inject the placeholder following the the newline character
file_get_contents($filename),
count($ads) // make the exact number of needed placeholders
),
$ads // replace the placeholders with the ad strings
)
);
I'm looking to increment a number after a certain letter.
I have a list of own Ids and i would like to increment it without write it manually each time i add a new id.
$ids = array('303.L1', '303.L2', '303.L3', '303.L4');
so i use the END() function to extract the last id from this array.
this is what i've tried but i cannot get a result.
$i = 0;
while($i <= count($ids)){
$i++;
$new_increment_id = 1;
$final_increment = end($last_id) + $new_increment_id;
}
echo $final_increment;
New method, but it is adding me double dot between number and letter.
$i = 0;
while($i <= count($ids)){
$i++;
$chars = preg_split("/[0-9]+/", end($ids));
$nums = preg_split("/[a-zA-Z]+/", end($ids));
$increment = $nums[1] + 1;
$final_increment = $nums[0].$chars[1].$increment;
}
//i will use this id to be inserted to database as id:
echo $final_increment;
Is there another way to increment the last number after L ?
Any help is appreciated.
If you don't want a predefined list, but you want a defined number of ids returned in an $ids variable u can use the following code
<?php
$i = 0;
$number_of_ids = 4;
$id_prefix = "303.L";
$ids = array();
while($i < $number_of_ids){
$ids[] = $id_prefix . (++$i); // adds prefix and number to array ids.
}
var_dump($ids);
// will output '303.L1', '303.L2', '303.L3', '303.L4'
?>
I'm a bit confused because you say "without write it manually". But I think I have a solution:
$ids = array('303.L1', '303.L2', '303.L3', '303.L4');
$i = 0;
while($i <= count($ids)){
++$i;
//Adding a new item to that array
$ids[] = "303.L" . $i;
}
This would increment just that LAST number, starting at zero. If you wanted to continue where you left off, that'd be simple too. Just take $i = 0; and replace with:
//Grab last item in array
$current_index = $ids[count($ids) - 1];
//Separates the string (i.e. '303.L1') into an array of ['303', '1']
$exploded_id = explode('.L', $current_index);
//Then we just grab the second item in the array (index 1)
$i = $exploded_id[1];
I have a keyspace in cassandra with columnfamily(let A) which is having composite key
another column family(let B) i am storing an exact number of rows which exist in the A column family. when i am fetching the data using multiget it's not giving the actual sorted data.
A: [1] = 13;
B:
[6014:2:0] = "aaaaaa";
[6014:2:1] = "bbbbbb";
[6014:2:2] = "cccccc";
[6014:2:3] = "dddddd";
[6014:2:4] = "eeeeee";
[6014:2:5] = "ffffff";
[6014:2:6] = "gggggg";
[6014:2:7] = "hhhhhh";
[6014:2:8] = "iiiiii";
[6014:2:9] = "jjjjjj";
[6014:2:10] = "kkkkkkk";
[6014:2:11] = "lllllll";
[6014:2:12] = "mmmmmmm";
my code
require_once(__DIR__.'/phpcassa/lib/autoload.php');
use phpcassa\Connection\ConnectionPool;
use phpcassa\ColumnFamily;
use phpcassa\SystemManager;
use phpcassa\Schema\StrategyClass;
$connection = new ConnectionPool('KEYSPACE', array('XXXX', 'YYYY', 'ZZZZ'));
$numDtls = new ColumnFamily($connection, 'A');
$key = 1;
$num_details = $numDtls->get($key);
$num = $num_details;
$json = '';
$key_array = array();
if(isset($num)){
$str = new ColumnFamily($connection, 'B');
for($i = 0;$i <= $num; $i++){
$key_array[] = array($table, $flag, $i);
}
$detail = $str->multiget($key_array);
$json = json_encode($detail);
}
its giving the output as
6014:2:0
6014:2:6
6014:2:9
6014:2:11
6014:2:4
6014:2:1
6014:2:12
6014:2:8
6014:2:7
6014:2:10
6014:2:3
6014:2:5
6014:2:2
it giving output in jumbled order...
How to get in sorted manner?
And how to get more than 100 rows?
Multiget makes no ordering guarantees, full stop. As to how to get more than 100 rows... you're asking the wrong question, large multigets are an antipattern. You need to denormalize so you can get the data you want with a single slice, instead. Check out my "timeline" example here: http://www.datastax.com/dev/blog/schema-in-cassandra-1-1
Right now I access each row and cells of a table like this:
$f = phpQuery::newDocumentFile('test.html');
// access row #1
$o = $f['#id tr:eq(0)'];
$d = phpQuery::newDocument($o);
// get cells from row #1
$arr[0]['c1'] = $d['td:eq(0)'];
$arr[0]['c2'] = $d['td:eq(1)'];
// access row #2
$o = $f['#id tr:eq(1)'];
$d = phpQuery::newDocument($o);
// get cells from row #2
$arr[1]['c1'] = $d['td:eq(0)'];
$arr[1]['c2'] = $d['td:eq(1)'];
I was wondering if there's a more efficient way of doing this? Like maybe if there's a way to find out the last index number then I can probably do something like this:
$f = phpQuery::newDocumentFile('test.html');
$last_index = 10;
for ($i = 0; $i <= $last_index; $i++)
{
$o = $f['#id tr:eq($i)'];
$d = phpQuery::newDocument($o);
$arr[$i]['c1'] = $d['td:eq(0)'];
$arr[$i]['c2'] = $d['td:eq(1)'];
}
Anybody knows how to find the last index (total number of rows in a table) ?
You can use the size() method.
$last_index = pq('#id tr')->size() - 1;