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,
Related
I'm training myself (JSON and PHP) and I have a problem
I have Json decode look like this :
"playerstats": {
"steamID": "75068112",
"gameName": "ValveTestApp260",
"stats": [
{
"name": "total_kills",
"value": 2314497
},
{
"name": "total_deaths",
"value": 1811387
},
And to parse into php i do :
$url = 'myrul';
$content = file_get_contents($url);
$json = json_decode($content, true);
echo $json['playerstats']['stats'][1]['name']
And it works but the problem is when i change the id to get stats, the order of the array isn't the same :/
So i can't use [2] or any else number to get data.
I post here to know how could'i get stats using the attribute name of each array ('total_kills' for example) instead of [1]..[2]..
thanks for all your support
Use foreach and use if condition to check the name is 'total_kills' is true then store it into new array like this .
<?php
$json = json_decode($content, true);
$new_array =array();
$i=0;
foreach($json['playerstats']['stats'] as $row )
{
if($row['name']=='total_kills')
{
$new_array[]=array($row['name']=>$row['value']);
}
if($i<10)
{
break;
}
$i++
}
print_r($new_array);
?>
$url = 'myrul';
$content = file_get_contents($url);
$json = json_decode($content, true);
foreach($json['playerstats']['stats'] as $row )
{
echo $row['name'];
echo $row['value'];
}
What you're looking for is a way to loop over the array. In PHP you can do the following;
$url = 'myurl';
$content = file_get_contents($url);
$json = json_decode($content, true);
foreach($json["playerstats"]["stats"] as $stat){
if($stat["name"] == "total_kills"){
echo "total kills: ".$stat["value"];
}
elseif($stat["name"] == "total_deaths"){
// ...
}
// etc... continue to select all parameters you would like
}
This will allow you to get the value for each stat with name using the if else statement.
Another way to do something with all objects in an array is to use the array_map() function, which takes another function as one of its arguments. Using this whenever you can will force you to adhere to good programming practices, because the passed in function cannot modify values outside of the array and arguments passed in via use.
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.
i have the problem to add elements to an json array.
The structure i want is that:
[{"method":"edit","type":"1", "template":"3", "meta":{"title":"Tools", "descirption":"Tools"}}]
The problem is that i add all these parameters dynamically.
So lets say i have for the start:
[{"method":"edit","type":"1", "template":"3"}]
How can i add the whole "meta" array and please do not be with push(), because than i will have another structure when i print it.
When i use
$json = json_decode($json, true);
I want to have:
array(
method' => edit,
'type' => 1,
'template' => 3,
'meta' => array('title' => '')
);
Thanks in advice !
So I'm going to assume you have the JSON to start with. So let's decode to PHP (as you noted correctly)
$json = json_decode($json, true);
So now we should have $json['method'], etc. Now let's define $meta
$meta = array('title' => '');
And add this to $json
$json['meta'] = $meta;
echo json_encode($json);
When your current JSON decodes in PHP using json_decode, it will decode into an array with one element, or array[0]. Therefore in order to access or any object you need to first point to that 0 index. Do it this way:
$json = '[{"method":"edit","type":"1", "template":"3"}]';
$arr = json_decode($json);
$arr[0]->meta = array('title' => '');
$json = json_encode($arr);
var_dump($json);
//Result:
// string '[{"method":"edit","type":"1","template":"3","meta":{"title":""}}]' (length=65)
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);
I have an array.
Array
(
[0] => Array
(
[title] => Badminton Men's Singles Gold Medal Kashyap Parupalli
[mp4] => http://www.tensports.com/media/video/kashyap.mp4
[webm] => http://www.tensports.com/media/video/kashyap_VP8.webm
[playThumb] => {filedir_2}Kashyap_medal.jpg
[videoPoster] =>{filedir_3}Kashyap_medal.jpg
)
[1] => Array
(
[title] => Boxing Men's Welter (69kg) Silver medal: Mandeep Jangra
[mp4] => http://www.tensports.com/media/video/MandeepJangraMedal.mp4
[webm] => http://www.tensports.com/media/video/MandeepJangraMedal_VP8.webm
[playThumb] => {filedir_2}Mandeep_Jangra_medal.jpg
[videoPoster] =>{filedir_3}Mandeep_Jangra_medal.jpg
)
)
I am trying to convert it in a object like below.
Javascript Format required :
videos = [
{
src : [
'http://www.tensports.com/media/video/kashyap_VP8.webm',
'http://www.tensports.com/media/video/kashyap.mp4'
],
poster : '{filedir_2}Kashyap_medal.jpg',
title : "Badminton Men's Singles Gold Medal Kashyap Parupalli"
},
{
src : [
'http://www.tensports.com/media/video/MandeepJangraMedal.mp4',
'http://www.tensports.com/media/video/MandeepJangraMedal_VP8.webm'
],
poster : '{filedir_2}Mandeep_Jangra_medal.jpg',
title : "Boxing Men's Welter (69kg) Silver medal: Mandeep Jangra"
}
];
what I have done :
var videoObject = $.parseJSON(<?php echo $js_VideoURL ?>);//where $js_VideoURL = json_encode($above-array);
$.each(videoObject, function(key, value) {
console.log('stuff : ' + key + ", " + value);
});
It's giving me error.I am uncertaing about getting the data in required format.Any help?
The format you're expecting in javascript is not compatible with the php array you've given.
Going from there I am assuming that is the problem, since you didn't give the exact error message you're encountering. From what I can gather you're missing a piece of PHP to put the video's in the correct format. To solve that you can do the following:
Note the comments in the code, they should explain what is going on.
PHP:
// $videos is assumed to be the array you've given in your question
$arr = [];
foreach ($videos as $video) {
// Create video object
$obj = new stdClass;
$obj->src = [
$video['webm'],
$video['mp4']
];
$obj->poster = $video['playThumb'];
$obj->title = $video['title'];
$arr[] = $obj;
}
// $arr is now the output you would need for processing
Javascript:
var videoObject = <?php echo $js_VideoURL ?>; //where $js_VideoURL = json_encode($arr);
$.each(videoObject, function(key, value) {
console.log('stuff : ' + key + ", " + value);
});
Edit:
Your first mistake is as Quentin mentioned that you're putting the json directly into javascript, which means it will be interpreted as a native javascript object. I missed that in my original answer.
It means you indeed do not need to use $.parseJSON to get the object you want. I changed my answer to reflect that.
Note:
Your code implies that you have Javascript snippets in your php / html templates. This is considered bad practice, and can be resolved with relative ease.
What you could do is put the json in a data attribute of the relevant html element on the page (escape the json before printing) then picking up the json string using jQuery on initialization with
var object = $element.data('json');
Using this (jQuery will automatically try parse the string as json) it will be ready for use.
The JSON format is a subset of JavaScript literal syntax
json_encode outputs JSON (which, if just dumped in JS, will be treated as a literal)
parseJSON takes a string of JSON and converts it to a data structure
Therefore: Don't use parseJSON as it will force the object you have into a string ("[Object object]") and then try to parse that as JSON.
Just:
var videoObject = <?php echo $js_VideoURL ?>;
Come on.. did you even check PHP docs, or even google json encode!?!?!
var videoObject = <?php echo json_encode($js_VideoURL); ?>;