I have an associative Array in PHP and I want to transfer it into an Javascript on the fly, how can I do that?
My PHP array looks something like this:
$pairs = ["LBo"=>"Large Blocks",
"Bo"=>"Blocks",
"bo"=>" blocky"]
I get the PHP array size into JS using
const pairsSize= "<?php print(count($pairs)); ?>"
Next I create a loop in which the indexname of the associative array and the assigned value has to be read from the PHP array. I'm stuck and I don't know how to do it.
let lithPairs = []; //my JS "associative" array
for (x = 0; pairsSize> x; x++) {
....
}
I want the result to look like this;
lithPairs['LBo']="Large Blocks";
lithPairs['Bo']="Blocks";
lithPairs['bo']="blocky";
any help would be much appreciated!
use json encode php array and fetch it using URL or Cookies/ localstorage
Related
I have a file called translations.js, this js does got have two vars. This two vars are containing over 20.000 words.
var english = ["word1", "word2", "word3", "word4", ...]
var farsi = ["translation1", "translation2", "translation3",
"translation3"]
So i want to add all the values to a table on mySQL.
How can I do that quick and good? I want to do this with PHP.
I have the table "translations", containing this columns: id, english, farsi.
I want that all the words should be added into the database. So i thought to split this file into english.js and farsi.js - after that I wanted to use "explode" on both variables, foreach till no "" is there and then i wanted to add them step by step.
Is there a easier way? Does this way make sense?
Thank you!
If those arrays are valid json by themselves you could make a json file for each and read the file using file_get_contents(), then use json_decode() to convert to php array.
Loop over array to do inserts.
Alternative would be to load those variables into an html page and use ajax to post the whole array to php script. Loop over array received in $_POST
Does have english array and farsi array exactly the same size?
(I suppose yes).
Maybe you can create a file english.json and a farsi.json;
each file must only contains ["word1", "word2", "word3"] so remove var english =.
then use
$listEnglish = json_decode(file_get_contents('path_to_english.json'));
$listFarsi = json_decode(file_get_contents('path_to_farsi.json'));
It should generate a php array for each one.
finally loop on it
for($i = 0; $i < sizeof($listEnglish); $i++)
{
$englishWord = $listEnglish[$i];
$farsiWord = $listFarsi[$i];
//Then you insert
INSERT INTO translation(english, farsi) VALUES ($englishWord, $farsiWord);
}
I have an array of file paths, which is stored in a PHP array called $files, which I would like to pass to a javascript array using this command:
var files = <?php echo json_encode($files)?>;
Which is fine, however it doesn't pass any values which have special characters for example one that contains 'æ'. Instead that value in Javascript comes out as null. Is there another way of preserving these characters? The values are all file paths, which seem to be passed over OK using json_encode, just not these special characters.
I've solved it. I essentially ran through the array using url_encode, and THEN JSON'd that for Javascript to interpret.
$filesEncoded = array();
foreach ($files as $f) {
array_push($filesEncoded,urlencode($f));
}
<script>
var files = <?php echo json_encode($filesEncoded)?>;
</script>
I have a MYSQL query that returns data using PDO::FETCHASSOC.
The array is then encoded using json.encode.
$row = $s->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($row);
The result is then passed to a javascript script using:
var percents = [];
percents.push(<?php get_percent('accantonamenti irreperibili', $pdo)?>);
Using console.log I see that percents is:
[[Object { perc_worst="-100", perc_best="-33"}]]
Question: how do I get perc_worst and perc_best values assigning them to two different values? percents.perc_worst doesn't work and either percents[0].perc_worst
BTW I can't get why the pair key value is created with = instead of :
Anyone can help??
Thanks!
Dont do .push().
Instead, do:
var percents = <?php get_percent('accantonamenti irreperibili', $pdo)?>;
Try accessing the values by:
console.log(percents.perc_worst);
console.log(percents.perc_best);
Keep it simple :)
I have the following JSON value pushed from the server.
result=[{"id":1492,"name":"Delhi"},
{"id":109,"name":"Coimbatore"},
{"id":576,"name":"Konni"},
{"id":525,"name":"Kottayam"}
]
I know how to convert JSON Array to Javascript Array.Here is the code below(got from stackoverflow)
var locations = [];
$.each(result, function(i, obj) {
locations.push([obj.id,obj.name]);
});
I want to convert this JSON Array to a JavaScript Object Array so that I can access the values as jarray[0].id which will give me the value 1492. Please advice
You don't need to do anything to the result array. Just use result[0].id and it will evaluate to 1492.
I've seen lots of articles on how to serialise arrays from javascript to send to PHP files which the PHP file will then deserialise back into an array, etc...
I have a large-ish nested associative array in my javascript which I need to save to a string and at a later date retrieve and convert back into a string in javascript. No other program will ever touch this. It may be handy if the serialised data is human-readable but it is absolutely not a requirement.
There is an intermediate PHP file but it's only 4 lines long: all it does is save the string to a file and send it back when requested. I'm not interested in parsing the array in PHP.
What is the fastest and simplest way to convert a multi-nested associative array in javascript to a string and back again?
JSON is a subset of the JavaScript language that is widely used as a serialization format, both for JavaScript and increasingly for other languages as well. It's human-readable, except that most implementations remove optional whitespace, which makes it a bit more difficult.
Modern browsers have JSON support out-of-the-box, for older ones you will need to include a library like json2.js.
To serialize, you use the JSON.stringify method.
var myObject = {a: 2, b: 3, c: [1, 2, 3]};
var serialized = JSON.stringify(myObject);
// serialized == "{"a":2,"b":3,"c":[1,2,3]}"
To unserialize, you use the JSON.parse method.
var recovered = JSON.parse(serialized);
Well, I have constructed my array like: var data = new Array(); data["John"] = "John Smith";
Ah, this is a problem. A JavaScript Array isn't meant to be used as an associative array, it's meant as a normal zero-indexed non-associative array. You can assign properties (key/value pairs) to any JavaScript object, which is why your code is working, but the fact thay your object is an Array is probably going to cause problems. If you just create a new Object() instead things should work better.
You'll want to serialize your array into JSON:
serialized = JSON.stringify(myobject)
To get it back
myobject = JSON.parse(serialized)
http://www.json.org/js.html
var someArray = [];
someArray.push({someObjectProperty: 'someValue' });
someArray.push({someObjectProperty: 'someValue2' });
console.log(someArray);
var stringVersion = JSON.stringify(someArray);//You can save the string version anywhere...
console.log(stringVersion);
var someNewArray = JSON.parse(stringVersion);
console.log(someNewArray);
Everyone has explained this well on the Javascript side, but this is how it happens on the PHP side:
<?php
$arr = Array(1, 2, 3, 'a', 'b', 'c'); // an array in PHP
echo json_encode($arr); // output the array as JSON: [1,2,3,'a','b','c']
?>
<?php
$json = "[1,2,3,'a','b','c']"; // a JSON string to be parsed by PHP
$arr = json_decode($json); // this is our original array in PHP again
?>