Break array down into unique arrays for database insert - php

I have an array like this:
Array
(
[year] => 1994, 1995, 1996, 1997
[make] => Ford
[model] => Mustang, Mustang Cobra, Mustang GT
[engine] => 302, 302 H/O, V6
)
I am wanting to insert unique rows into my database with all the possible solutions in the array.
For example:
id year make model engine
1 1994 Ford Mustang 302
2 1994 Ford Mustang Cobra 302
3 1994 Ford Mustang GT 302
4 1994 Ford Mustang 302 H/O
...and so on
I need to be able to break down that array to get all possible solutions into a unique row. Some columns may not have a value. For example, the array may only contain several Make's. I would like to insert all the unique possibilities into an array.
Array
(
[0] => 1994, Ford, Mustang, 302
[1] => and so on...
)

Here is simple way, without database part, but I hope you can do that yourself:
$arr = array
(
'year' => '1994, 1995, 1996, 1997',
'make' => 'Ford',
'model' =>'Mustang, Mustang Cobra, Mustang GT',
'engine' => '302, 302 H/O, V6'
);
$years = explode(',',$arr['year']);
$makes = explode(',',$arr['make']);
$models = explode(',',$arr['model']);
$engines = explode(',',$arr['engine']);
foreach($years as $year) {
foreach($makes as $make) {
foreach($models as $model) {
foreach($engines as $engine) {
echo 'INSERT INTO yourtable '.$year.', '.$make.', '.$model.', '.$engine."\n";
}
}
}
}

If you need "all unique possibilities" (combinations), the most direct approach is to iterate your information array nesting each item the other. And for each combination created from an iteration, create an array with the collected information and add to a final array. Eg:in kind of pseudo code
finalArray = new array()
foreach(year as y)
foreach(make as m)
foreach(model as mo)
foreach(engine as e)
newArray = new array(y,m,mo,e)
add newArray to finalArray
hope it heps you

Related

Can't get exactly values from other page

I am trying to get score table from this page http://www.skysports.com/football/competitions/bundesliga/table. I do this with
$bundes = file('http://www.skysports.com/football/competitions/bundesliga/table');
And when i try to display array $bundes i do it with this:
echo '<pre>', print_r($bundes), '</pre>';
The code witch i try do display is displayed like this:
[1437] =>
[1022] => German Bundesliga 2015/16
# Team Pl W D L F A GD Pts Last 6
1 [1059] => [1060] => Bayern Munich [1061] => [1062] => 9 9 0 0 29 4 25 27 [1072] =>
[1073] =>
[1074] =>
This is the first row of table. And now i can display $bundes[1060] and i get output of Bayer Munich but how can i get values from $bundes[1062], values are 9, 9, 0, 0, 29, 4, 25 and 27? I need to display each of this values in <td></td>
When i try to echo $bundes[1062] i get nothing.
A more reliable way of extracting the data is using DOM manipulation classes to do something like:
$doc = new \DOMDocument();
#$doc->loadHTMLFile('http://www.skysports.com/football/competitions/bundesliga/table');
$xpath = new \DOMXPath($doc);
$rows = $xpath->query('//tbody/tr');
$data = [];
foreach ($rows as $i => $row) {
$columns = $xpath->query('td', $row);
foreach ($columns as $column) {
$data[$i][] = trim($column->textContent);
}
}
print_r($data);
Which gives you:
Array
(
[0] => Array
(
[0] => 1
[1] => Bayern Munich
[2] => 9
[3] => 9
[4] => 0
[5] => 0
[6] => 29
[7] => 4
[8] => 25
[9] => 27
[10] =>
)
...
Regarding Dagon's comment, no terms can disallow crawling and extracting the data (as long as you do so at a reasonable rate that does not impact the website's performance). Terms of use & copyright law, however, do dictate what you can and cannot do with the crawled content (ex. republish).
Web scraping may be against the terms of use of some websites. The enforceability of these terms is unclear (see "FAQ about linking – Are website terms of use binding contracts?").
- Wikipedia, Web scraping: Legal issues
BTW, the pages robots meta tag does allow INDEX.

PHP & MySQL, laying out in CSV format with special parameters

I have a database that has budgets in them (for this, I have modified the budgets to be fake).
Long story short, I am attempting to run the following SQL query on the database, and then display a report based on it.
Here is the query: SELECT MONTHNAME(date) AS month, product, SUM(amount) AS spend FROM client_budgets WHERE advertiser_id = '$advertiser_id' GROUP BY MONTHNAME(date), product ORDER BY MONTH(date) ASC
I then clean the data a little, here is the code for that:
foreach($data AS $key => $val) {
$clean_data[] = $val;
}
From this, I get the following (this is a PHP array of the data. I have cut it off since it has about 100K rows in the database currently).
Array
(
[0] => Array
(
[month] => January
[product] => Internet
[spend] => 12000.00
)
[1] => Array
(
[month] => January
[product] => Radio
[spend] => 12250.00
)
[2] => Array
(
[month] => February
[product] => Billboards
[spend] => 6000.00
)
[3] => Array
(
[month] => February
[product] => Internet
[spend] => 16000.00
)
)
My goal is to end up being able to display in a CSV (I already have the headers set for the CSV), the following:
Month, Internet, Radio, Billboards, Television
January, 12000, 12250, 6000, 0
February, 16000, 7000, 6000, 2000
....
I am stuck right now trying to sort the data correctly, and if there is no data for Television for instance one month, to display a 0. Any help would be appreciated! I have been attempting this for almost 3 days now.

How to create json data from multidimension array (each month in year)

I need to export a set of json data for highchart. But I'm having a problem with looping.
I've got 2 set of arrays:
Years Array (2015,2014,2013,2012) - form MySQL
Month Array (01,02,03,04,05,06,07,08,09,10,11,12)
So I make it in array - multidimensional. With this code.
$sql_arrYr=mysqli_query($con,"select year(bk_date1) as arrYr from booking_db group by year(bk_date1) order by arrYr asc");
while($rec_arrYr=mysqli_fetch_array($sql_arrYr)){
$arrYr[$rec_arrYr['arrYr']]=array("01","02","03","04","05","06","07","08","09","10","11","12");
}
Then I've got:
Array ( [2015] => Array ( [0] => 01 [1] => 02 [2] => 03 [3] => 04 [4] => 05 [5] => 06 [6] => 07 [7] => 08 [8] => 09 [9] => 10 [10] => 11 [11] => 12 )...);
Which is looking good coz I have all data I need in a set of arrays - year and each month values.
So I continue with fetching data from mySQL with this code.
foreach($arrYr as $key=>$val){
$rows=array();
$rows[type]='spline';
$rows[name]=$key;
foreach($val as $mon){
$sql_nBk=mysqli_query($con,"select count(*) as nBkr from booking_db where year(bk_date1)='$key' and month(bk_date1)='$mon'");
$rec_nBk=mysqli_fetch_array($sql_nBk);
$rows[data][]=$rec_nBk['nBkr'];
}
}
echo json_encode($rows);
The problem happened here. It's not loop. The only line I've got is.
{"type":"spline","name":2015,"data":["9","8","0","0","0","0","0","0","0","0","0","0"]}
Which I expect this:
{"type":"spline","name":2015,"data":["9","8","0","0","0","0","0","0","0","0","0","0"]}
{"type":"spline","name":2014,"data":["9","8","0","0","0","0","0","0","0","0","0","0"]}
{"type":"spline","name":2013,"data":["9","8","0","0","0","0","0","0","0","0","0","0"]}
{"type":"spline","name":2012,"data":["9","8","0","0","0","0","0","0","0","0","0","0"]}
Please give me a reason why it's not loop. Even I put them in a right loop.
You are setting $rows to an empty array each time through the outer loop. Also, you can't have duplicate keys. The first type is overwritten by the next (also name and data) so you have to make it multidimensional. You can use the $key variable for this to make it easy, or implement a counter $i and use $i++ or something.
$i = 0;
foreach($arrYr as $key=>$val){
$rows[$i]['type']='spline';
$rows[$i]['name']=$key;
foreach($val as $mon){
$sql_nBk=mysqli_query($con,"select count(*) as nBkr from booking_db where year(bk_date1)='$key' and month(bk_date1)='$mon'");
$rec_nBk=mysqli_fetch_array($sql_nBk);
$rows[$i]['data'][]=$rec_nBk['nBkr'];
}
$i++;
}
echo json_encode($rows);

How to utilize method with RegEx in order to print into a dynamic table on with PHP

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.

Order array items based on their occurrence desc in php

I have an array of mysql records in $allrecords variable.
There are multiple keys for each record and one of the key is called type.
Some of the variable has the same type.
E.g. it looks like this:
Seat
Mercedes
BMW
BMW
Mercedes
Audi
Mercedes
Fiat
Mercedes
Audi
Fiat
Mercedes
The array is unordered now (just grabbed from database) and now I need to order the array items from the most occurance one to the least.
E.g. like this
Mercedes (5)
Audi (3)
BMW (2)
Fiat (2)
Seat (1)
I do not need the numbers (that I get using another foreach loop), so I need it just like this:
Mercedes
Audi
BMW
Fiat
Seat
How to do such this in PHP? Is it possible? I need to group the items based on the type and then order them from the most to the least occurance.
Thanks in advance.
EDIT:
My array look like this:
Array
(
[0] => stdClass Object
(
[id] => 125
[user_id] => 29
[show] => 1
[state] => 1
[type] => 23
[subcat_id] => 11
[category_id] => 2
[name] => SLK 350
)
)
<?php
$groups = array();
foreach($allrecords as $record){
$type = $record->type;
if(empty($groups[$type]))
$groups[$type] = 1;
else
$groups[$type]++;
}
asort ($groups);
$cars = array_keys($groups);
print_r($cars);
usort($allrecords, function($a, $b){ return $a->count >= $b->count; });
where "count" is the name of the property...
var_dump(str_word_count(implode(" ", $all_records))); // Returns array( "Mercedes" => 5 ... )
aaaah i didn't get that!!!
you should use SQL to achieve this!!!
SELECT type, COUNT(1) FROM cars GROUP BY type;

Categories