I have a database with strings and which language this string belongs. A string has a unique name, which I use to identify it, and then a translation for each language.
With PHP, I get this information from the database and store it in an associative array like:
$languages['strings']['lang']['unique_string_name'] = $translation;
Now, as I want my Javascript code to be translated too, I need to pass it to. I've tried doing it in JSON, but some $translation have quotes and double quotes, and it's a hell to escape and get it all correct - because escaping just escapes the whole JSON string, not only translation.
So, what I've done is loop the whole array and echoing the $translation in a Javascript associative array again, but this time with addslashes - only the translation.
However, if I look to the Source Code, I see 600 lines of Javascripts entries, one for each translation (of course, this has nothing strange, just simply UGLY).
I was wondering if there's a much cleaner way of passing this translation array to my Javascript code without having to loop the PHP array and echo it to a JS variable.
Thanks for your time and answers!
All you really need is:
<script type="text/javascript">
var languages = <?php echo json_encode($languages); ?>;
</script>
You'll end up with an exact duplicate of your PHP array in JS, so
echo $languages['strings']['lang']['unique_string_name']; // PHP
alert(languages.strings.lang.unique_string_name); // JS
will both bring up the same translation.
Related
var jsonString = '{"DeviceId":3,"results":{"1":"[{\"x\":513,\"y\":565,\"width\":175,\"hight\":208}]"}}';
var message = JSON.parse(jsonString);
I got an error saying Unexpected token u in JSON at position 0
at JSON.parse.
Could you please guide me what's wrong?
THanks in advance!
At the last few characters looks wrong. The :212 has no sense as the value (that long array) for key "1" was already set, so that later :212 looks weird
Also enclosing it in single quotes it makes that all be like a huge string, and not as an array structure.
See Results key as value contains a sub array which contain "1" key which as value contains a string enclosing another json array (but escaped as plain string, so no structurally accesible for the main object . But that string if post -processed the :212 is paired to what? , no key, no comma neighter , to the precedent whole array which already was the value, not the key?. Anyway weird.
In your JSON string, there is wrong something with ":212", as it's not valid JSON, because it doesn't have any property that it's mapping the value for. For example, you are mapping values for width and height with properties keys. But for "212", there is no property.
Here is the above JSON formatted:
var jsonString = '{"DeviceId":"3","results":{"1":"[{\\"x\\":513,\\"y\\":565,\\"width\\":175,\\"hight\\":208}]"}}'
var message = JSON.parse(jsonString);
If you want to format the results, you can do to it, there is no error on it:
JSON.parse(message.results['1'])
Here is the JS Bin link for above code: https://jsbin.com/fiyeyet/edit?js,console
Just an advice
Professional code is all about proper spacing, proper identation , proper commenting, don't try to write down all within one single line, structure it VISUALLY nice to see nice to read nice to comprehend, and you will be approved in most jobs.
Hint: declare a normal array/object , convert it to json string using the proper function, then use the string variable returned by the function to test your code or whatever doing. That way, you can write down in the source really nice the structure.
-- Edit 2--
I'm placing this on top since I'm narrowing down on the problem.
I send this string nested within a bigger array the combines all the attributes for a WP shortcode. The problem lays within the square brackets.
{“key”:”post_type”,”value”:[“news”,”agenda"]}
My best ques is that I need to escape the square brackets or to search replace on both sides and use a placeholder like (squareBracketOpen).
Or is there another way to serialize/unserialize an array?
The problem lays within the square brackets.
-- / Edit 2 --
I’m working in React and PHP and I’m tying to add something on top of a Wordpress Plugin. This uses React, which I’m not familiar with at all :)
Right now I have zero knowledge of react, but I’m getting stuff to work bit by bit. There is one thing though I don’t know how to solve. I’ll start with the quesion:
How do I serialise a multidimensional array in React and unserialise it in PHP?
If, in any case I miss translate my question, let me state my goal as following:
I have an multidimensional array in React and I want to pass it to PHP and reuse it as an multidimensional array.
This would be the array:
Array {
[key] => “post_type”,
[value] => Array {
[0] => “news”,
[1] => “agenda”
}
}
As a test in React I do
console.log(JSON.stringify(post_type));
// expected return {“key”:”post_type”,”value”:[“news”,”agenda"]}
--edit-- I've noticed it adds [ ] brackets as multidimensional. That's not right, right? -- end edit--
Looks fine to my knowledge, right?
Now in PHP I try to unserialise it with:
var_dump( unserialize ($postType ) );
// result: bool(false)
So I’m obvious doing something wrong. :)
Would anyone know how to properly serialise the multidimensional array in React and unserialise it in PHP to an array?
You'll need to do a json_decode($post_type, true) for it to be converted into a multi dimensional array.
Note, the second parameter true is what converts it to associative array.
So essentially, you'll be doing JSON.stringify then json_decode() for it work in php
Alright, finally. What I ended up doing is on the js/react side.
Serialize array to string. with JSON.stringify()
uri encoded the string. with encodeURIComponent()
And on the php side reversed it.
JS/React
let post_type_encoded = encodeURIComponent( JSON.stringify( post_type ) )
PHP
$postType = json_decode ( urldecode( $postTypeEncoded ) );
UPDATE!! My code is actually valid to run. The original question is below. If you are still curious please read the question and then back to read my update.
My bad, the db actually can get updated successfully after the code runs. I accidentally set the datatype in the table as INT but my initial intention, varchar.
But from HenryDev's answer I managed to find the acquired array by post method in php becomes STRING type but array type. I used
$cameArray = $_POST['cameArray'];
echo gettype($cameArray);
to output "string" on my screen, so implode would not work oh that(see the discussions on HenryDev's answer).
However his answer will work as a charm if you set up an array in PHP and implode it, it will give you back a "string type" of your array!
UPDATE!! My code is actually valid to run. The original question is below. If you are still curious please read the question and then back to read my update.
Here is my original question
So I have a very basic question but the tutorials and answers I found online are kinda complicated for my situation.
I have a JS array like
var sentArray = ['1','2','3'];
I want to insert this array into the database as one field of a table. I use ajax to send this array to PHP and then execute the query in PHP. For instance,
$cameArray = $_POST['cameArray']; //then $cameArray is sentArray
mysqli_query($con, "INSERT INTO thisTable (arrayField) VALUES ($cameArray)");
And then I want the value in the database shown as "1, 2, 3", but the problem is the value in the database is simply shown as a single "2". The type in table is varchar.
No any JSON object involved just pure text. How could I do that? Thanks!
Here's a quick solution. If you want to store the array as an string simply do this in your PHP code.
$array = array('1', '2', '3'); // Your array
$cameArray = implode(",", $array);
echo $cameArray; // "1,2,3"
Now you can store the variable $cameArray in your Data Base. Hope it helps!
My bad, the db actually can get updated successfully after the code runs. I accidentally set the datatype in the table as INT but my initial intention, varchar.
But from HenryDev's answer I managed to find the acquired array by post method in php becomes STRING type but array type. I used
$cameArray = $_POST['cameArray'];
echo gettype($cameArray);
to output "string" on my screen, so implode would not work oh that(see the discussions on HenryDev's answer).
However his answer will work as a charm if you set up an array in PHP and implode it, it will give you back a "string type" of your array!
Before I describe the issue, please forgive any incorrect terms and accidental references to objects instead of arrays and vice-versa, I'm not completely up to speed on this but working my way through it.
I have the following array in PHP saved as a session variable:
{"CategoryF":[],"CategoryA":["Life","There","People","Land","Family"],"CategoryC":["Various"]}
After a thumbnail in a grid of images is dragged into a new order, it execute a function in javascript and makes a call to a PHP script using ajax. It currently only retrieves the most up to date version of a session array. It will later progress to make the necessary steps to save the updated array back to session variable and database:
var sorty = Sortable.create(thumbcontainer, {
animation: 250,
draggable: "img",
dataIdAttr: 'id',
onUpdate: function (/**Event*/evt) {
var orderList = sorty.toArray();
var catsArray =
$.ajax({
type: 'POST',
url: 'includes/proc_cats.php',
dataType: 'json'
}).done(function(returnedCatsArray) {
console.log(returnedCatsArray);
});
console.log('Dragged. Order is: ' + orderList);
}
});
proc_cats.php
<?php
// Access the existing session
session_start();
// $catsArray is a session variable, in the format as above.
$catsArray = json_encode($_SESSION['categoriesPics']);
echo $catsArray;
?>
The var orderList will produce a string with the order of each thumbnail by id, separated by comma: '42,35,95,12,57'.
The console shows the PHP array as a javascript array fine but in a different order. I want to be able to insert the string containing the orders into the array and save it back into the database. It will associate with its relevant category, similar to:
{"CategoryF":[],"CategoryA":["Life":["23,74,47,12,86,83,12"],"There","People","Land","Family"],"CategoryC":["Various"]}
But can't lose the order as other parts of the site reference the array by indices using array_keys. The console produces:
Object:
CategoryA:Array[0]
CategoryC:Array[0]
CategoryF:Array[5]
Have I missed something? I believe that the overall array is an object rather than an array because it didn't have any index whereas the subcategories did and they get presented as an array. array_keys in PHP have made it straightforward enough to work around any indexing problems up until now on the PHP side in other areas of the site but I'm wondering if the solution for the javascript side is something as straightforward? The subcategories currently have indices only because I've yet to associate and orderList with them so I'm not trying not to backtrack and build an index for the array as it's going to get difficult (unless there's a simple way to do this that I've overlooked).
(This is a more specific version of a question I asked an hour ago that I've now deleted for being too broad).
I believe you have a slight confusion based on the terms 'associative array' and 'array'. A php associative array corresponds to a javascript object. returnedCatsArray should be accessed similar to $catsArray. ie. with keys. If one of those keys returns an an actual array, you can then index into it.
php array_keys would be Object.keys(returnedCatsArray) in javascript.
From further research it appears this is just not doable. So the best way to do this may be to provide an order array alongside my category array.
If I add the additional code of:
$parentCatOrder = array_keys($catsArray);
in my proc_cats.php script I have a concise way of generating an index reference for my original array on the fly each time. This produces an array similar to:
$parentCatOrder = {'categoryF', 'categoryA', 'categoryC'};
which has an index that I can refer to that keeps its order. So $parentCatOrder[2] will always produce 'categoryC' unless I've changed the array myself.
I then return both arrays to javascript using the following:
$return_data['catsarray'] = $catsArray;
$return_data['parentcatsorder'] = $parentCatOrder;
// Encode it back into a JSON object before sending
echo json_encode($return_data);
In javascript I can reference returnedCatsArray.catsarray[returnedCatsArray.parentcatsorder[1]][3] if I'm working with an index of 1-3 and guarantee this will produce the same result for every user unless the array has been changed by the user.
I know that I can create an associative array like this:
var MyAssocArray = {'sky':'blue', 'grass':'green'};
And I am very fond of using this method.
What I would like to do and am having trouble with is this:
I have strings saved like this:
var MyString = "'sky':'blue', 'grass':'green'";
And I want to be able to do this now:
var MyAssocArray = {MyString};
When I try that - I get this error:
invalid object initializer
What am I doing wrong?
How can I achieve this?
I found a different solution using PHP and JavaScript. The associative array string is echoed in the JavaScript code:
var Multidimensional_Arr[Multidimensional_Array_Key_Name] = {<?php echo $String_Pulled_From_Database; ?>}; // i.e. 'sky':'blue', 'grass':'green'
// The same can be done for a one-dimensional array
var My_Single_Dime_Arr = {<?php echo $String_Pulled_From_Database; ?>}; // i.e. 'sky':'blue', 'grass':'green'
Use JSON -- it's serialized JavaScript Object Notation and is pretty close to what you're doing.
You'd need to do
var MyAssocArray = JSON.parse(MyString);
Also, JSON uses double quotes, not single quotes; if you use simple objects, you can probably write code to just replace ' with "" in your strings, but it's tricky if the strings contain double-quotes.
If you are using a browser that doesn't implement JSON.parse(), you can either use the implementation on the JSON website (see links at bottom of this page) or if you're using jQuery, there's jQuery.parseJSON().
Warning: Your solution has a security risk, unless you are sure the data in the database has been sanitized:
var My_Single_Dime_Arr = {<?php echo $String_Pulled_From_Database; ?>}
This is equivalent to a call to eval(); if your database string has any malicious code it can do bad things. This is one reason why JSON was invented -- it's easy to ensure that its contents are valid (and hence safe) before evaluated.
Your overall architecture, as you have presented it to us, is [data in database] -> server-side PHP -> client-side JavaScript. This is a classic example of serialized data. I realize you may have constraints to keep your system running without interruption, but a strict serialization format would make your system more secure.
If you are sure the data is safe, then you could do:
var MyAssocArray = eval('{' + MyString + '}');
You can't do that.
To achieve what you want, use the split() function to split your string into comma-separated tokens first. Then each token should further be split by the ':' character.
Then push the two tokens obtained by the last split as the key and the value of your associative array.