I currently have a script that parses a text file with (for example) 100 lines, from 10 different users, and for each line pulls out a $userName, $timestamp and a variety of other things. Is there a way that I can loop through (after it does the parsing) and work with 1 group of $userName at a time.
The end goal is to enter the data into google docs 1 user at a time.
I have tried using $i and $i++ however due to the fact that my primary loop is an array within an array things get a little goofy.
What I would like is the ability to see the following
$userName | $timeStamp
mhopkins321 | 13-12-30
mhopkins321 | 14-59-01
mhopkins321 | 19-32-59
You just have to make the proper array structure:
$users = array(
'mhopkins321' => array(
'13-12-30',
'14-59-01',
...
),
'anotherUser' => array(
...
)
);
So when you're parsing, and run into a username and timestamp:
$users[$username][] = $timestamp;
And when you want to make that table
foreach($users as $user) {
foreach ($user as $timestamp) {
echo $user."| ".$timestamp."\n";
}
}
...probably with better formatting, but there ya go.
Related
EDIT:
I want to thanks #jimmix for giving me some idea to get started on my last post, But unfortunately, my post was put on hold. Due to the lack of details.
But here are the real scenario, I'm sorry if I didn't explain well my question.
From my CSV file, I have a raw data, then I will upload using my upload() function in into my phpmyadmin database with the table name "tbldumpbio",
See the table structure below:(tbldumpbio)
From my table tbldumpbio data, I have a function called processTimesheet()
Here's the code:
public function processTimesheet(){
$this->load->model('dbquery');
$query = $this->db->query("SELECT * FROM tbldumpbio");
foreach ($query->result() as $row){
$dateTimeExplArr = explode(' ', $row->datetimex);
$dateStr = $dateTimeExplArr[0];
$timeStr = $dateTimeExplArr[1];
if($row->status='C/Out' and !isset($timeStr) || empty($timeStr) ){
$timeStrOut ='';
} else {
$timeStrOut = $dateTimeExplArr[1];
}
if($row->status='C/In' and !isset($timeStr) || empty($timeStr) ){
$timeStrIn ='';
} else {
$timeStrIn = $dateTimeExplArr[1];
}
$data = array(
'ID' => '',
'companyAccessID' => '',
'name' => $row->name,
'empCompID' => $row->empid,
'date' => $dateStr,
'timeIn' => $timeStrIn,
'timeOut' => $timeStrOut,
'status' => '',
'inputType' => ''
);
$this->dbquery->modInsertval('tblempbioupload',$data);
}
}
This function will add another data into another table called "tblempbioupload". But here are the results that I'm getting with:
Please see the below data:(tblempbioupload)
The problem is:
the date should not be duplicated
Time In data should be added if the status is 'C/In'
Time Out data should be added if the status is 'C/Out'
The expected result should be something like this:
The first problem I see is that you have a time expressed as 15:xx:yy PM, which is an ambiguous format, as one can write 15:xx:yy AM and that would not be a valid time.
That said, if what you want is that every time the date changes a row should be written, you should do just that: store the previous date in a variable, then when you move to the next record in the source table, you compare the date with the previous one and if they differ, then you insert the row, otherwise you simply progress reading the next bit of data.
Remember that this approach works only if you're certain that the input rows are in exact order, which means ordered by EmpCompId first and then by date and then by time; if they aren't this procedure doesn't work properly.
I would probably try another approach: if (but this is not clear from your question) only one row per empcompid and date should be present, i would do a grouping query on the source table, finding the minimum entrance time, another one to find the maximum exit date, and use both of them as a source for the insert query.
I'll note that this is a very special case, hence the question to begin with. Under normal circumstances, such a function would be simple:
I have an array named $post_id, which contains 5 values
(Each numerical)
In order to print each value in the array, I use the following loop:
.
for ($i = 0; $i < $num; $i++)
{
echo $post_id[$i] . ' ';
}
...Which prints the following: 49, 48, 47, 46, 43
3. In my database, I have a table that looks like this:
post_categories
_____________________
post_id | category
__________|__________
43 | puppies
43 | trucks
46 | sports
46 | rio
46 | dolphins
49 | fifa
4. So, using the data in the array $post_id, I'd like to loop a database query to retrieve each value in the category column from the post_categories table, and place them into uniquely named arrays based on the "post id", so that something like...
echo $post_id_49[0] . ' ', $post_id_46[1];
...Would print "fifa rio", assuming you use the above table.
An example of such a query:
//Note - This is "false" markup, you'll find out why below
for ($i = 0; $i < $num; $i++)
{
$query = "SELECT category FROM post_categories WHERE post_id = $post_id[$i]";
fakeMarkup_executeQuery($query);
}
Why is this a "special" case? For the same reason the above query is "false".
To elaborate, I'm working inside of a software package that doesn't allow for "normal" queries so to say, it uses it's own query markup so that the same code can work with multiple database types, leaving it up to the user to specify their database type which leaves the program to interpret the query according to the type of database. It does, however, allow the query to be stored in the same "form" that all queries are, like "$result = *query here*" (With the only difference being that it executes itself).
For that reason, functions such as mysql_fetch_array (Or any MySQL/MySQLi function akin to that) cannot, and will not work. The software does not provide any form of built in alternatives either, effectively leaving the user to invent their own methods to achieve the same results. I know, pretty lame.
So, this is where I'm stuck. As you'd expect, all and any information you find on the Internet assumes you can use these MySQL & MySQLi functions. What I need, is an alternative method to grab one array from the results of a looped query per loop. I simply cannot come to any conclusion that actually works.
tl;dr I need to be able to (1) loop a query, (2) get the output from each loop as it's own array with it's own name, and (3), do so without the use of functions like mysql_fetch_array. The query itself does not actually matter, so don't focus on that. I know what do with the query.
I understand this is horrifically confusing, long, and complicated. I've been trudging through this mess for days - Close to the point of "cheating" and storing the data I'm trying to get here as raw code in the database. Bad practice, but sure as heck a lot easier on my aching mind.
I salute any brave soul who attempts to unravel this mess, good luck. If this is genuinely impossible, let me know so that I can send the software devs an angry letter. All I can guess is that they never considered that a case like mine would come up. Maybe this is much more simple then I make it to be, but regardless, I personally cannot come to an logical conclusion.
Additional note: I had to rewrite this twice due to some un explained error eliminating it. For the sake of my own sanity, I'm going to take a break after posting, so I may not be able to answer any follow up questions right away. Refer to the tl;dr for the simplest explanation of my need.
Sure you can do this , here ( assuming $post_ids is an array of post_id that you stated you had in the OP ), can I then assume that I could get category in a similar array with a similar query?
I don't see why you couldn't simply do this.
$post_id = array(49, 48, 47, 46, 43);
$result = array();
foreach($post_id as $id)
{
//without knowing the data returned i cant write exact code, what is returned?
$query = "SELECT category FROM post_categories WHERE post_id = $id";
$cats = fakeMarkup_executeQuery($query);
if(!empty($cats)) {
if(!isset($result[$id])){
$result[$id] = array();
}
foreach( $cats as $cat ){
$result[$id][] => $cat;
}
}
}
Output should be.
Array
(
[49] => Array
(
[0] => fifa
)
[46] => Array
(
[0] => sports
[1] => rio
[2] => dolphins
)
[43] => Array
(
[0] => puppies
[1] => trucks
)
)
Ok, assuming you can run a function (we'll call it find select) that accepts your query / ID and returns an array (list of rows) of associative arrays of column names to values (row), try this...
$post_categories = [];
foreach ($post_id as $id) {
$rows = select("SOME QUERY WHERE post_id = $id");
/*
for example, for $id = 46
$rows = [
['category' => 'sports'],
['category' => 'rio'],
['category' => 'dolphins']
];
*/
if ($rows) { // check for empty / no records found
$post_categories[$id] = array_map(function($row) {
return $row['category'];
}, $rows);
}
}
This will result in something like the following array...
Array
(
[49] => Array
(
[0] => fifa
)
[46] => Array
(
[0] => sports
[1] => rio
[2] => dolphins
)
[43] => Array
(
[0] => puppies
[1] => trucks
)
)
I would first like to thank you for taking the time to look at my question--I am quite novice at PHP/CodeIgniter programming, however, I enjoy it very much.
What I am trying to do:
1) Retrieve each CompanyId associated with the company when the user is logged in. I achieve this by passing the $CompanyId (in my controller) from the session as a parameter to a query in my model. I have this working well as such:
// Assign query result to array to be used in view
$data['campaigns'] = $this->model_record->retrieve_campaign($CompanyId);
2) The return value is an array nested as such:
Array (
[campaigns] => Array (
[0] => Array (
[CampaignId] => 1
[DID] => 2394434444
[FWDDID] => 3214822821
[ProductId] => 1
[CampaignName] => Fort Myers Bus #1
[ProductName] => CallTrack - Sharktek
[Active] => 1
[CompanyId] => 1 )
)
3) Once this is processed, I am trying to create a for each loop that queries each CampaignId through another query in my model. Due to the MVC pattern I am implementing, I have to pass the results of this query to my $data array to send to the view.
foreach($data['campaigns'] as $campaign) {
$ids[] = $campaign['CampaignId'];
}
foreach ($ids as $row) {
$data['ids'] = $this->model_record->week_data(0,$row, $StartDate);
}
4) I am then trying to test view all the results of my queries in my view, however, I am only receiving one value, but when I echo the results of the foreach of the CampaignIds, it they all show up. Does anyone have any suggestions?
<?php
foreach($ids as $row):
echo $ids['MyCount'];
endforeach
?>
5 Extra) I have not begun to approach this yet, but once I get this working, I would like to run the query week_data 7 times as it is returning the data for each day of the week. My assumption is that I would place a for loop until it hits 7, is this correct?
Thank you again, for attempting to help me--I greatly appreciate the work many of you put into this community.
This line:
$data['ids'] = $this->model_record->week_data(0,$row, $StartDate);
Should look like:
$data['ids'][] = $this->model_record->week_data(0,$row, $StartDate);
As it is, the first line overwrites $data['ids'] until all you're left with is the last one. You need to add them to an array to collect all of them.
I have a table with various entries such as start date (contract), some random documents and monthly invoices and receipt in it, like this:
DOCUMENT TYPES
ID TYPE CHECK? MONTHLY?
1 Contract Yes No
2 Documents No No
3 Policy Yes No
4 Order No No
5 Invoice Yes Yes
6 Receipt Yes Yes
DOCUMENTS
ID TYPE DATE
1 1 01/01/2013
2 2 01/01/2013
3 3 01/01/2013
4 5 01/02/2013
5 6 01/02/2013
6 4 14/02/2013
7 5 01/03/2013
8 6 01/03/2013
TODAY 05/05/2013
My goal is to produce the output as shown below.
Display all existent documents, where CHECK? is Yes, and display missing documents where MONTHLY? is Yes.
01 Contract 01/01/2013 OK
02 Documents 01/01/2013 OK
03 Policy 01/01/2013 OK
04 Invoice 01/02/2013 OK
05 Receipt 01/02/2013 OK
06 Invoice 01/03/2013 OK
07 Receipt 01/03/2013 OK
08 Invoice 01/04/2013 Missing
09 Receipt 01/04/2013 Missing
10 Invoice 01/05/2013 Missing
11 Receipt 01/05/2013 Missing
I have written some code, but I not understand how to include monthly loop to display invoices and receipts.
QUERY
// Get type
$query = "SELECT * FROM doc_type
WHERE check='1'";
$result = mysql_query($query) or die(mysql_error());
$num = mysql_numrows($result);
// Get docs
$check = array();
$query2 = mysql_query("SELECT document_type_id FROM documents");
while ($row = mysql_fetch_assoc($query2)) {
$check[] = $row['document_type_id'];
WHILE
<tbody>
<?php
$i=0;
while ($i < $num) {
$document_type_id = mysql_result($result,$i,"document_type_id");
$document_type = mysql_result($result,$i,"document_type");
?>
<tr class="grade">
<td><?php echo $document_type_id; ?></td>
<td><?php echo $document_type; ?></td>
<td>
<?php
if (in_array($document_type_id, $check)) {
echo "<p style='color:green'>Ok</p>";
} else {
echo "<p style='color:red'>Miss</p>";
}
?>
</td>
</tr>
<?php
$i++;
}
?>
</tbody>
First, I must point out that I am slightly confused by the example data, because it looks like you are loading the data from a database for the first table, but the example implies that there is a list of documents that is being saved elsewhere for each job or project.
If it were me, I'd create either an object or an array representing your final table. That object you can then fill based on the available data. Given the data structure that you seem to be already using, I will assume that you would rather not use an Object Oriented Programming approach.
First, create an array or object that stores your original table information that matches the document type and the monthly setting. Once you choose a data format, you can load the data format from your database for each different group of settings. I will use the settings you have shown in your example.
Personally, I'd use the document type id as the index key and use boolean values to represent Yes (true) and No (false) like this:
$doc_requirements = array(
1 => array( "name" => "Contract", "check" => true, "monthly" => false ),
2 => array( "name" => "Documents", "check" => false, "monthly" => false ),
3 => array( "name" => "Policy", "check"=>true, "monthly"=>false ),
4 => array( "name" => "Order", "check"=>false, "monthly"=>false ),
5 => array( "name" => "Invoice", "check"=>true, "monthly"=>false ),
6 => array( "name" => "Receipt", "check"=>true, "monthly"=>false )
);
Use your database to store as many of these tables as you need and load them before reviewing your document list.
Next I would create an array that represents the output table. Index it by date so you can determine if you have missing documents. Your data implies that on each date, that we can have more than one document, but not more than one document of the same type, so you might be able to use something like this:
/* pseudo_code */ $temp_table = array(
[date] => array(
[doc_type_name] => array(
/* I assume that the document id is actually just the line number
on the table, so I will leave the id out of this, but if it is
not just the line on the table, add this field to the array:
"id" => [id], */
"status" => [status] )
),
[doc_type_name] => array(
"status" => [status] )
),
...
),
[date2] => array( ... ),
....
);
Load this array with the documents that you know about from your document array:
(note: you are using the mysql functions, which are currently deprecated, so you should look at using the msyqli functions instead)
$sql = #### /* SQL query string for your list of documents that are not missing */
$result = mysql_query($sql) or die(mysql_error());
if($result){
while( $document = mysql_fetch_assoc( $result ) ){
$date = $document[ "date" ];
$doc_type_id = $document[ "type_id" ];
$doc_type_name = $doc_requirements[ $doc_type_id ]["name"];
$temp_table[ $date ][ $doc_type_name ]["status"]= "OK"
/* we have the document, therefore, we know it is okay,
we can set that value immediately */
}
}
$start_date=#### /* set start date of contract */
$end_date=##### /*set end date of contract */
foreach( $doc_requirements as $requirement ){
if( $requirement["monthly"] == true ){
for( $cur_date = $start_date; $cur_date <= $end_date; $cur_date=#### ){
/*increment the date by whatever function you choose,
I recommend using a DateTime object
for your dates and incrementing by using the add() method */
$current_doc_name = $requirement[ "name"];
if( !isset( $temp_table[$cur_date][ $current_doc_name ] ) ){
/* if the array value is not set,
then a document of the type_name
and current date specified does not exist,
because the requirement for "monthly" == true,
we know that we should have it, so we will
set the status to "Missing" */
$temp_table[$cur_date][$current_doc_name]["status"] = "Missing";
}
}
}
}
Now we have an array organized by date, containing one document record for each document that we have a record of in our database (but no more than one of each type per date...If you need to change this, just change the data structure of the array to match your needs or use an object oriented approach that helps map out your thoughts more naturally). For any item that is Monthly = true (YES) we have a "Missing" stub created for it indicating that something was expected there but not found. Having this data array, we can cycle through it and produce the output.
I have noted above that your document id appears to just be the line number on the output table, so I will represent it the same way here:
$doc_id = 1;
foreach($temp_table as $cur_date){
foreach($cur_date as $doc_name){
$doc_id_string = your_func_format_id( $doc_id );
/* use whatever function you like to make your doc_id two digits.
Perhaps printf() would be useful */
$color_code = "style='color:green'";
if( $doc_name["status"]=="Missing" ) $color_code = "style='color:red'";
echo "<tr class='grade'><td>$doc_id_string</td><td>$doc_name</td><td>$cur_date</td><td><p $color_code>{$doc_name["status"]}</p></td>";
}
}
I have learned that using the correct data structure makes everything more simple. I have tried to use a data structure that reflects your example code. I highly recommend using Object Oriented Programming (OOP) techniques to implement your designs, because OOP forces every programmer to consider the shape of the data before considering the programming code, and it solves many problems.
What is the best way in PHP to do variable caching? For example, let's assume I have a table, with 4 rows.
name | job
--------------------------
Justin Smith | Plumber
Jack Sparrow | Carpenter
Justin Smith | Plumber
Katie White | Doctor
Which is built like:
foreach($people as $person) {
echo $person->name;
echo get_job($person->name);
}
And the function call get_job() looks like:
function get_job($name) {
//This is pseudo code below
$row = MySQL->Query("SELECT job FROM people WHERE name = $name");
return $row->job;
}
As you can see, once we get the job of Justin Smith, further down we shouldn't and don't need to do a full MySQL query again, since we know it is Plumber.
I was thinking of doing a global variable which is a key=>value array like:
global $jobs = array("Justin Smith" => "Plumber",
"Jack Sparrow" => "Carpenter",
"Katie White" => "Doctor");
Then in the get_job() function I simply just check if the name exists in the array before querying. If not, insert the name and job into the array and return the job.
Basically, is there a better way to do this that is more elegant?
There is many possible solutions. You can store the SQL result in an array that you can use on multipe places on the page. Instead of global you should use static:
function get_job($name)
{
static $people_jobs;
if( !isset($people_jobs[$name]) || empty($people_jobs[$name]) )
{
$row = MySQL->Query("SELECT job FROM people WHERE name = $name");
$people_jobs[$name] = $row->job;
}
return $people_jobs[$name];
}
This function will do a MySQL query only once for a person, no matter how many time you call get_job($name);
this is the typical n + 1 problem where you make 1 query to get the list of "person" and then you make one query for each person to get the "job".
Depending how they are related.. maybe you could get both using one single query. For example: if the relation is a Nx1 (1 person has 1 Job, and 1 job can be used for N Persons) then your initial query should be something like:
SELECT p.name, j.job FROM Person p INNER JOIN Job j ON (p.job_id = j.id)
If the relation is a NxN, it gets tricky :P,
Hope this helps