I'm using the the League CSV library, but the same exact thing happens when I use built in PHP functions. Here is my spreadsheet:
ID column A column B column C
123 apple orange pear
And here is my code:
$stmt = (new Statement())
->offset(0)
->limit(2)
;
$records = $stmt->process($csv);
foreach ($records as $record) {
print_r($record);
}
Finally, here is the output. Notice, the ID value (123) is hanging off to the left. I'm not even sure what that is supposed to mean.
Array
(
[0] => ID
[1] => column A
[2] => column B
123 [3] => column C
[4] => apple
[5] => orange
[6] => pear
)
Edit: Here is the raw CSV file. Newline character is possibly a carriage return?
ID,column A,column B,column C
123,apple,orange,pear
This was really lame. Since I'm on a Mac, I needed to add this line to the top of the script:
ini_set('auto_detect_line_endings',TRUE);
Related
I have this module where the user first generates the blank CSV, which only contains the headers, that is six fields. Out of those 6 fields, 3 fields are filled while the other 3 are empty.
for example:
A, B, C, D, E, F. So the values that A, B, C contain are coming from database using the query.
Now, when user fills in D, E, F and uploads the the sheet, a problem arises. I had set this condition that whenever D & E & F are 0, it will delete that particular ID, that is A. So the particular entry with 0,0,0 will be deleted. It worked fine for a while, but now the deletion has stopped working, I don't know why. I figured out a lot, but couldn't get the solution.
Here are my code snippets.
$sql = "SELECT query......";
$outlet_locality_array = $DB->query($sql);
if(isset($outlet_locality_array[0]->minimum_order)
&& isset($outlet_locality_array[0]->delivery_time)
&& isset($outlet_locality_array[0]->delivery_charge))
{
if(($outlet_locality_array[0]->minimum_order == 0)
&& ($outlet_locality_array[0]->delivery_time == 0)
&& ($outlet_locality_array[0]->delivery_charge == 0))
{
$condition_check = array();
$condition_check['outlet_locality_id'] = $outlet_locality_array[0]->outlet_locality_id;
$DB->delete(PLATFORM_OUTLET_LOCALITIES,$condition_check);
}
}
Now when I tried debugging, the first IF statement executed, but the second IF statement did not execute. When I debug the variable $outlet_locality_array, I get all the values except the 0. And when I see the response that ajax sends, the data there shows me that the csv file that was uploaded has a 0.
So where am I missing out???
the response that i get is this:
csv_data:Location Id,City Name,Location Name,Minimum Order Amount,Delivery Time,Delivery Charge
5,East,Park,213,69,12123
6,East,Garden,2782,123,234
12,East,Phase 2,12345,345,2345
837,West,College,0,0,0
This is when I debug the array $outlet_locality_array
Array( [0] => stdClass Object ( [outlet_locality_id] => 44104 [minimum_order] => 213 [delivery_time] => 69 [delivery_charge] => 12123 ))
Array( [0] => stdClass Object ( [outlet_locality_id] => 44105 [minimum_order] => 2782 [delivery_time] => 123 [delivery_charge] => 234 ))
Array( [0] => stdClass Object ( [outlet_locality_id] => 44106 [minimum_order] => 12345 [delivery_time] => 345 [delivery_charge] => 2345 ))
Right now I'm using the command below to get the volume names of the mounted disks in OSX:
$exec = "df -lH | grep \"/Volumes/*\" | tr -s \" \" | sed 's/ /;/g'";
And parsing the output using this code:
$lines = explode("\n", $output);
$i = 0;
foreach ($lines as $line) {
$driveinfo = explode(";", $line);
$driveinfo[7] = trim($driveinfo[0]);
if (!empty($driveinfo[0]))
$allremovabledrives[$driveinfo[0]] = $driveinfo;
$i++;
}
This works fine if the Volume label doesn't have spaces in it:
[/dev/disk1s1] => Array
(
[0] => /dev/disk1s1
[1] => 32G
[2] => 31G
[3] => 674M
[4] => 98%
[5] => 0
[6] => 0
[7] => /dev/disk1s1
[8] => /Volumes/LUMIX
)
But if I mount a disk with a volume name that has spaces, disaster strikes and extra array values get added:
[/dev/disk4] => Array
(
[0] => /dev/disk4
[1] => 4.0T
[2] => 1.2T
[3] => 2.8T
[4] => 29%
[5] => 140741078
[6] => 347553584
[7] => /dev/disk4
[8] => /Volumes/My
[9] => Passport
[10] => Pro
)
Can anybody help me solve this problem? I'm not well versed in sed and command-line utilities ...
OK, the volume name is always the last field, and you know how many fields there are (9), so I would just split on whitespace and ask for that many fields. And not bother with any sed/awk/grep/tr stuff since you're already in a full-fledged programming system that can do what those commands do more efficiently within its own process space.
First, you can pass the list of volumes you want info about to df as arguments, which means you don't need the grep:
$df = shell_exec('df -lH /Volumes/*');
Now split on newline and get rid of the headers:
$rows = explode("\n", $df);
array_shift($rows);
Start building your result:
$result = array();
Here's where we don't need to use shell utilities just to make it possible to do with explode what we can already do with preg_split. The regular expression /\s+/ matches 1 or more whitespace characters in a row, so we don't get extra fields. The limit (9) means it only splits into 9 fields no matter how many more spaces there are - so the spaces in the last field (the volume name) get left alone.
foreach ($rows as $row) {
$cols = preg_split('/\s+/', $row, 9);
$result[$cols[0]] = $cols;
}
After all that, $result should look like you want.
I have a list of courses and the hours they require for students to take them. The courses are as follows:
CON8101 Residential Building/Estimating 16 hrs/w
CON8411 Construction Materials I 4 hrs/w
CON8430 Computers and You 4 hrs/w
MAT8050 Geometry and Trigonometry 4 hrs/w
I have used this RegEx to extract the name of course and the hours each course takes each week. There are more than 4 courses, the 4 are examples above. There can be as many as 50 courses.
$courseHoursRegEx = "/\s[0-9]{1,2}\shrs/w/";
$courseNameRegEx = "/[a-zA-Z]{3}[0-9]{4}[A-Z]{0,1}\s?/[a-zA-Z]{3,40}/";
And applied the following function (not sure if 100% right) to extract the RegEx'd strings. Using $courseLine is the variable I saved the string of each line from a text document that early I have fopened. It keeps track of the total hours that has been extracted from the string.
$courses is an array of check boxes that the user enters in the html section
$totalHours += GetCourseHours($courseLine);
function GetCourseHours($couseLine)
{
if(!preg_match($courseHoursRegEx, $courseLine))
{
return $courseLine;
}
}
function GetCourseName($courseLine)
{
if(!preg_match($courseNameRegEx, $courseLine))
{
return $courseLine;
}
}
I used a foreach loop to output all the selected courses to be sorted out in a table.
foreach($courses as $course)
{
$theCourse = GetCourseName($course);
$theHours = GetCourseHours($course)
}
Edit: output code
for($i = 1; $i <= $courses; ++$i)
{
printf("<tr><td>\$%.2f</td><td>\$%.2f</td></tr>", $theCourse, $theHours);
}
I am not sure how to output what I have into a dynamic table organized by the course name, and hours for each course. I cannot get my page to run, I cannot find any syntax errors, I was afraid it was my logic.
First of all, (after fixing a few minor things within the regexes) you can do all of that in one preg_ call. Here is how:
preg_match_all("~([a-zA-Z]{3}\d{4}[A-Z]{0,1}\s.+)\s(\d{1,2})\shrs/w~", $str, $matches);
$str can either be a multiline string with all rows at once. Or you can pass in a single line at a time. If you pass in all lines at once, $matches will afterward look like this:
Array
(
[0] => Array
(
[0] => CON8101 Residential Building/Estimating 16 hrs/w
[1] => CON8411 Construction Materials I 4 hrs/w
[2] => CON8430 Computers and You 4 hrs/w
[3] => MAT8050 Geometry and Trigonometry 4 hrs/w
)
[1] => Array
(
[0] => CON8101 Residential Building/Estimating
[1] => CON8411 Construction Materials I
[2] => CON8430 Computers and You
[3] => MAT8050 Geometry and Trigonometry
)
[2] => Array
(
[0] => 16
[1] => 4
[2] => 4
[3] => 4
)
)
Now you can simply iterate over all names in $matches[1] and sum up the hours in $matches[2]. Notice that those two inner arrays correspond to what's inside of the round brackets I used in the regex. These are so called subpatterns, and they capture additional (sub-)matches. Also $matches[0] will always contain the full match of the whole pattern, but you don't need that in this case.
I'm trying to code a search function for a site written on CodeIgniter but have trouble with the join statement in the model.
A controller passes an array of search criteria to the model function: get_sales($search_criteria);
function get_sales($search_criterie){
$this->db->join('sales_prices', 'sales_prices.sale_id = sales.sale_id', 'left');
$this->db->join('sales_sizes', 'sales_sizes.sale_id = sales.sale_id', 'left');
$query = $this->db->get_where('sales', $search_criterie);
$sale_data = $query->result_array();
}
I'm running into two problems:
1) I need a WHERE clause in the sales_sizes join. Right now it joins sales_sizes.sale_id ON sales.sale_id but I want to be able to filter by size via the $search_criteria array. How can I do this?
2) Every sales usually has multiple sizes and I want the output of the query formatted like:
Array
(
[sale_id] => 1
[sale_category] => shoes
[sale_price] => 29.99
[sale_sizes] => Array
(
[0] => 10
[1] => 10.5
[2] => 11
)
)
I've tried some foreach loops to format the output but can't get it to work. Hope somebody can help.
Update:
How do I process the following query result into a format like the one above?
Array
(
[0] => Array
(
[sale_id] => 1
[sale_category] => shoes
[sale_price] => 29.99
[sale_size] => 10
)
[1] => Array
(
[sale_id] => 1
[sale_category] => shoes
[sale_price] => 29.99
[sale_size] => 10.5
)
[2] => Array
(
[sale_id] => 1
[sale_category] => shoes
[sale_price] => 29.99
[sale_size] => 11
)
)
I am personally not a big fan of using the active record as given. I find that it often restricts the programmer from writing more complex queries. If you find that this is true as well you could rewrite your query as followed:
$this->db->query('SELECT * FROM `sales_prices`, `sales_sizes` WHERE `sales_prices`.`sale_id` = `sales`.`sale_id` AND `sales_sizes`.`sale_id` = `sales`.`sale_id` AND `sales` = ?', array($search_criterie));
$sale_data = $query->results();
This will generate the same result and will also parameterize your query. Note that the question mark corresponds in order to values in your array that will make up the second parameter of you $this->db->query() function.
Try this type of query
$this->db->select('places.*, category.*')
->from('places')
->join('category', 'places.category_id = category.category_id', 'left')
->join('places_reviews', 'places_reviews.place_id = places.id', 'left')
->where('places.category_id', $category_id)
->limit($limit, $offset)
->order_by($sort_by, $sort_order);
The below solution will work for you, it won't generate exact output, but very close to one.
$this->db->select('sales.*, GROUP_CONCAT(DISTINCT sales_prices.sale_id) as sales_price GROUP_CONCAT(DISTINCT sales_sizes.sale_id) as sales_size')
This will generate a comma separated value for you.
I have mysql search results from a keyword search being performed on my site. They're sorted by membership rank (0-3). However, I need to display the ranks differently than each other - like rank 3 gets more prominent formatting than the others.
I was thinking of splitting the rows up into individual arrays. So like array0 would contain all the rows that had the rank of 0, etc. Then loop through these arrays to display the results. I just have NO idea how to do this -- split the array up into smaller arrays.
(For reference, I found this question: splitting a large array into smaller arrays based on the key names but I wasn't really sure if that's what I needed... maybe some clarification on that q would help here?)
For example here is my array:
Array (
[rank] => 3
[organization] => Test Company
[imagecompany] => 1636.gif
[website] => http://www.google.com
[phone] => 344-433-3424
[fax] =>
[address_on_web] => physical
[address] => 2342 Test Ave
[city] => York
[stateprov] => WA
[postalcode] => 00000
[address_mailing] => 2342 Test Ave
[city_mailing] => Seattle
[state_mailing] => WA
[zip_mailing] => 00000
[description] => 'Test test Test test Test test Test test Test
test Test test Test test Test test Test test Test test Test test Test test Test test
Test test Test test'
[customerid] => 1636 )
You can use the rank as a key to create an multidimensional array like this:
$aRanks = array();
foreach($aArray as $aEntry) {
$aRanks[$aEntry['rank']][] = $aEntry;
}
echo '<pre>';
print_r($aRanks);
I have mysql search results from a keyword search
Then sort it using the database/SQL - not PHP. It's faster and uses less code.
$query = mysql_query(); // your query here
$result = mysql_fetch_array($query);
foreach($result as $row){
switch($row['rank']){
case 3:
// statement to apply formatting, add to each case
// example:
echo "<span style="color:red;">;
break;
case 2: break;
case 1: break;
}
}
Then output each row, echo closing </span> (or div or whatever) where you want the formatting to end