i have some problems with CSV files.
I have about 50 csv files, all looks the same like this below.
I need to import them into Php array - (later i put them into js var, and use in diagrams)
But the CSV dont looks like should do (i cant change it) - It have some data at top (first 10 lines) - i need to use them in different places (just show them - like "Kategoria:";"ROLNICTWO, LEŚNICTWO I ŁOWIECTWO"; - is a title)
"Okres sprawozdawczy:";"Dane roczne";
"Kategoria:";"ROLNICTWO, LEŚNICTWO I ŁOWIECTWO";
"Grupa:";"SKUP PRODUKTÓW ROLNYCH";
"Podgrupa:";"Skup produktów na 1 ha użytków rolnych";
"Wymiary:";"Wykaz produktów, Lata";
"Kod";"Jednostka terytorialna";"buraki cukrowe";"buraki cukrowe";"buraki cukrowe";"buraki cukrowe";
"2010";"2011";"2012";"2013";
"[kg]";"[kg]";"[kg]";"[kg]";
"1100000000";" ŁÓDZKIE";"278";"355";"363";"333";
"1140000000";" MAZOWIECKIE";"247";"250";"286";"348";
"2120000000";" MAŁOPOLSKIE";"67";"87";"114";"127";
"2240000000";" ŚLĄSKIE";"168";"218";"245";"281";
"3060000000";" LUBELSKIE";"1139";"1170";"1235";"1346";
"3180000000";" PODKARPACKIE";"249";"208";"342";"404";
"3200000000";" PODLASKIE";"6";"30";"5";"0";
"3260000000";" ŚWIĘTOKRZYSKIE";"479";"482";"337";"534";
"4080000000";" LUBUSKIE";"184";"141";"264";"229";
"4300000000";" WIELKOPOLSKIE";"1102";"1412";"1485";"1532";
"4320000000";" ZACHODNIOPOMORSKIE";"522";"830";"909";"642";
"5020000000";" DOLNOŚLĄSKIE";"1044";"1045";"1274";"1136";
"5160000000";" OPOLSKIE";"1392";"1386";"2113";"1660";
"6040000000";" KUJAWSKO-POMORSKIE";"1588";"2040";"2272";"2252";
"6220000000";" POMORSKIE";"624";"748";"724";"879";
"6280000000";" WARMIŃSKO-MAZURSKIE";"153";"150";"163";"167";
How i can print them as array - to looks like this:
[0] => Array
(
[0] Okres sprawozdawczy
[1] Dane roczne
)
[1] => Array
(
[0] Kategoria
[1] ROLNICTWO, LEŚNICTWO I ŁOWIECTWO
)
[2] => Array
(
[0] Grupa:
[1] SKUP PRODUKTÓW ROLNYCH
)
etc. first 5 lines of CSV lines.
But later from line 7 (6 is empty) - line 7,8,9 is one header..
"Kod" - its "1100000000"
"Jednostka terytorialna" - its "ŁÓDZKIE"
"buraki cukrowe","2010","[kg]" - "278"
"buraki cukrowe","2011","[kg]" - "355"
"buraki cukrowe","2012","[kg]" - "363"
"buraki cukrowe","2013","[kg]" - "333"
3 headers for one data, so i need i think something like that:
[6] => Array ([0] buraki cukrowe => Array ([0] 2010 => Array ([0] kg => Array ([0] 278)
Where the "278" is data what i need to use and put in to JS VAR.
Im not sure its good way to do this, please help me out..
First you set this file on variable, you can use file_get_content() like this
$csvData = file_get_contents('your_file.csv');
you can do it for all the files you need to add
After you have your $csvData you just have to explode and chunk it like this
$explodedCsvData = explode(';',$csvData);
$chuckedCsvData = array_chunk($explodedCsvData,2);
Something like that could do the trick :
$file = fopen('your-file.csv');
$header = true;
$headers = [];
$data = [];
while($line = fread($file)) {
if($line === '') { // Transition from headers to columns info
$header = false;
$line = fread($file);
$label = explode(';', $line);
$l = count($label);
$year = array_pad(explode(';', fread($file)), -$l, null);
$unit = array_pad(explode(';', fread($file)), -$l, null);
$column = [];
for($i=0; $i<$l; ++$i) {
$column[] = [
'label' => $label[$i],
'year' => $year[$i],
'unit' => $unit[$i]
];
}
}
elseif($header) { // Still in the first lines
$headers[] = explode(';', $line);
}
else { // After the columns parsing
$data[] = explode(';', $line);
}
}
fclose($file);
Related
I've been searching for a few days now, trying to figure out the best way to solve a problem: I want to fetch a JavaScript file from e.g. GitHub and convert a JavaScript array into PHP.
My first idea was to fetch the page (raw.githubusercontent.com) with PHP (file_get_contents) on server side and then parse it. But it's a multidimensional array, so I think this is complicated and not very flexible.
Example
In JavaScript only the keys are relevant (e.g. https://raw.githubusercontent.com/xxx/example.js)
var cars = {
'Saab': {
'Blue': true,
'Green': true,
...
},
'Volvo': {
'Brown': true
},
'BMW': {
'Black': true
},
...
}
In PHP the content should be combined as a string array:
Array
(
[0] => 'SaabBlue'
[1] => 'SaabGreen'
[2] => 'VolvoBrown'
[3] => 'BMWBlack'
...
)
I would be happy if someone had an idea a short hint ;)
Update:
I think I will do this server side with PHP.
$arr = array();
// fetch the file
$content = file_get_contents('https://raw.githubusercontent.com/xxx/example.js');
// remove all comments and unnecessary lines with RegEx
$content = preg_replace(<RegEx Expression>, '', $content);
foreach(preg_split("/((\r?\n)|(\r\n?))/", $content) as $line){
// filter with strpos and/or preg_match
// [x][ ][ ]
if ( filter ) {
$m = explode("'", $line);
// [ ][x][ ]
} else if ( anyfilter) {
$n = explode("'", $line);
// [ ][ ][x]
} else if ( filter ){
$o = explode("'", $line);
$str = $m[1] . $n[1] . $o[1];
array_push($arr, $str);
}
}
Set all the variables into cookies.
document.cookie = "cars_Saab_Blue="+cars.Saab.Blue;
Do something similar (dpending on the situation) and set everything into 1 or more cookies.
Now by using $_COOKIE['cars_Saab_Blue'] you can get the cookie and use it wherever you want,
This question already has answers here:
PHP json_decode integers and floats to string
(6 answers)
Closed 3 years ago.
I am trying to add multiple markers into a google map and i have found a way to do that here.
Now I have a json array response from the server as shown below.
// function to get user names and addresses
public function getUserAddresses(Request $request)
{
$users = User::where('address', '!=', null)->select('name', 'address')->get(); //this is a laravel query
$userData = [];
foreach ($users as $user) {
$userData[$user->name] = $user->address;
}
return $userData;
}
This code above is what gives me the response below.
{
"plumber1": "-1.2523238641713191,36.87899683074249",
"plumber2": "-1.2192245641713191,36.87899687428849",
"allan plumber": "-1.2192238641713191,36.87899683068849"
}
but for me to use this data it must be in these format as shown below in javascript.
[
["plumber1", -1.2523238641713191,36.87899683074249],
["plumber2", -1.2192245641713191,36.87899687428849],
["allan plumber", -1.2192238641713191,36.87899683068849]
];
You can use this php code
$str = '{
"plumber1": "-1.2523238641713191,36.87899683074249",
"plumber2": "-1.2192245641713191,36.87899687428849",
"allan plumber": "-1.2192238641713191,36.87899683068849"
}';
$array =json_decode($str);
$new_array = [];
foreach ($array as $key => $value) {
$coordinates = explode(',',$value);
$coordinate1 = (float) $coordinates[0];
$coordinate2 = (float) $coordinates[1];
$new_array[] = array($key,$coordinate1,$coordinate2);
}
print_r($new_array);
OUTPUT
Array
(
[0] => Array
(
[0] => plumber1
[1] => -1.25232386
[2] => 36.878996830742
)
[1] => Array
(
[0] => plumber2
[1] => -1.2192245641713
[2] => 36.878996874288
)
[2] => Array
(
[0] => allan plumber
[1] => -1.2192238641713
[2] => 36.878996830688
)
)
You can also check the demo here
Here is Javascript version
<script type="text/javascript">
var str = `{
"plumber1": "-1.2523238641713191,36.87899683074249",
"plumber2": "-1.2192245641713191,36.87899687428849",
"allan plumber": "-1.2192238641713191,36.87899683068849"
}`;
var obj = JSON.parse(str);
var array = [];
var counter =0;
for (var key in obj) {
var myarr = obj[key].split(",");
array[counter] = [key, parseFloat(myarr[0]), parseFloat(myarr[1])];
counter++
}
console.log(array);
</script>
Try json_decode
ini_set( 'precision', 17 );
$jsonToArray = json_decode($json, JSON_NUMERIC_CHECK);
I am having array problems and need help simplifying the answer. Now without me pasting and typing out from a greasemonkey script(Javascript), I am just pasting a little code from it:
//THIS LINK IN BROWSER IS WHAT IM GETTING FROM THE JS SIDE OF THE CODE. NOW I CAN GET THE DATA= , ID=, AND &SA=,&DA=, &SPY=, AND &SENTRY=.
//THE &WEAPONS=0,4674,72|1,19,71|1,370,51|2,300,75|2,239,73|3,482,74|3,354,68
/php/Armory.php?data=ID=4518188&GOLD=6559178&SA=1805135169&DA=22677617&SPY=2841765807&SENTRY=2703794914&WEAPONS=0,4674,72|1,19,71|1,370,51|2,300,75|2,239,73|3,482,74|3,354,68
I am having problems in my PHP to separate the array after &WEAPONS=. I've tried several things like split or even array_chunk, and all I get is the same answer which is what shows after weapons= part when I echo or print_r.
I want to separate this into 3 sections in PHP then have SQL insert the answer into the database if at all possible...
Below is some of the code I've done in PHP.
<?php
$list = $_REQUEST['WEAPONS'];
$list = explode("^", $list);
print_r(array_chunk($list, 3));
?>
OUTPUT:
Array ( [0] => Array ( [0] => 0,4674,72|1,19,71|1,370,51|2,300,75|2,239,73|3,482,74|3,354,68 ) )
I want this part divided up into 3 parts for a table on DB which is stat, wcount, and weaponNr.
0,4674,72|1,19,71|1,370,51|2,300,75|2,239,73|3,482,74|3,354,68
When divided up it will look like this:
stat = 0
count = 4674
weaponNr = 72
--------
stat = 1
count = 19
weaponNr = 71
--------
stat = 1
count = 370
weaponNr = 51
etc.....
--------
Sorry for the long explanation but if anyone can help, I'd appreciate this cause I am not a pro at coding or asking how lol...
To separate the string into an array this works:
function weaponsToArray($string) {
$weapons = [];
foreach (explode('|', $string) as $dataRow) {
$data = explode(',', $dataRow);
$weapons[] = [
'stat' => $data[0],
'count' => $data[1],
'weaponNr' => $data[2],
];
}
return $weapons;
}
$weapons = weaponsToArray($_GET['WEAPONS']);
i need to create chart based on php array and i found something about traversing in stackoverflow posts but those answers doesnt help for converting this:
Array
(
[product sample 1] => Array
(
[0] => Array
(
[hitsTotal] => 63
)
[1] => Array
(
[hitsTotal] => 113
)
)
[product sample 2] => Array
(
[0] => Array
(
[hitsTotal] => 57
)
[1] => Array
(
[hitsTotal] => 107
)
)
)
to
['product sample 1', 63, 113],
['product sample 2', 57, 107]
how to convert?
Assuming $input is the array you present in your post you can do the following:
$output = array();
foreach($input as $key => $value)
{
$obj = array();
$obj[] = $key;
$obj[] = $value[0]['hitsTotal'];
$obj[] = $value[1]['hitsTotal'];
$output[] = $obj;
}
var_dump($output); //This will print it on screen so you can validate the output
To prepare your data for passing to js(client side) as an array of arrays use the following approach (array_walk, array_column, array_merge and json_encode functions):
// supposing that $arr is your initial array
$result = [];
array_walk($arr, function($v, $k) use(&$result){
$hitsTotals = array_column($v, 'hitsTotal');
$result[] = array_merge([$k], $hitsTotals);
});
echo json_encode($result);
The output:
[["product sample 1",63,113],["product sample 2",57,107]]
I have this array value: print_r ($array); which contains 2 data (this is latt and long of my gmap project).
The array is from:
<?php
if(isset($_GET['q'])) {
$q = $_GET['q'];
}
$q = isset($_GET['q']) ? $_GET['q'] : '';
$array = array();
$nsUser="SELECT * FROM cliententry WHERE kampusterdekat=:q";
$uQuery = $mydb->prepare ($nsUser);
$uQuery->execute(array(':q' => $q));
while ($result = $uQuery->fetch(PDO::FETCH_ASSOC)) {
$id=$result['id'];
$googlemap=$result['googlemap'];
//echo $googlemap;
$array[] = $googlemap;
print_r ($array);
}
?>
When I echo, the result will be like this:
Array
(
[0] => -5.364000343425874, 105.24465411901474
)
Array
(
[0] => -5.364000343425874, 105.24465411901474
[1] => -5.362878747789552, 105.24150252342224
)
Point:
What I need is to make the result into this format:
var wwwsitus = [
['<h4>area</h4>', wwwsitus[0]],
['<h4>area</h4>', wwwsitus[1]],
];
where locations (<h4>area</h4>) are removed. So, it must be, as follows:
var wwwsitus = [
[...,...],
[...,....],
];
Note:
Since I've no capable about array in JS, please help me to fix my title based on my issue. Thks in adv.