$cw = array(chr(0)=>455,chr(1)=>455,...,'E'=>521,...chr(134)=>353,chr(135)=>353,...chr(255)=>465);
I have this file that defines an array as seen above (I have just shown a bit of the array for conciseness). Is this array assigning integer values to all of the ascii characters? If so why and also, how do I convert it to JavaScript?
I don't find it appropriate to explain to you why your code is defining any variables of an array, but please see this post on how to convert a php array to javascript.
https://stackoverflow.com/a/5619038/367456
Or you may use
var js_array = [<?php echo '"'.implode('","', $php_array).'"' ?>];
Related
I have two PHP strings that looks like this (obviously shortened for the question):
$year [
[0]=>2003
[1]=>2003
[2]=>2004
[3]=>2004
[4]=>2005
[5]=>2005
]
$cost [
[0]=>200
[1]=>300
[2]=>400
[3]=>500
[4]=>410
[5]=>510
]
I need to turn the PHP arrays above into a JAVASCRIPT array formatted exactly as below:
var newData=[
['2003', 200,300],
['2004', 400,500],
['2005', 410,510]
];
When I type in the JS array implicitly (as above) all works fine (ie the graphics render correctly). However after several hours of trying different approaches, I cannot work out how to easily generate the newData array dynamically (ie from PHP arrays as shown) in exactly the JS Array format shown.
Your quest can be separated in two tasks:
First of all you want to combine both arrays. I guess you want to do this based on the keys they have. There are multiple functions for that in PHP, like array_combine or array_reduce.
Yet for your case the easiest way is a for_each loop, because you have duplicate values in the $year array.
$combined_array = [];
foreach ($year as $id => $year_val) {
if (!array_key_exists($year_val, $combined_array)) {
$combined_array[$year_val] = [(string)$year_val];
}
$combined_array[$year_val][] = $cost[$id];
}
Now you have the years as keys, what you do not want, so you can use array_values to remove the keys again.
$combined_array = array_values($combined_array);
The second task is quite easy: Go to the PHP file, that loads the script you want to provide the array to. Add this before you load the script:
<script>
var myPhpArray = <?php echo json_encode($combined_array) ?>;
</script>
After that the PHP array is accessible from JS in the variable `myPhpArray.
if you respect the structure in the example, the following would do the job:
<?php
$year = [
0 => 2003,
1 => 2003,
...
];
$cost = [
0 => 200,
1 => 300,
...
];
for($i=0;$i<SIZE_OF_ARRAY;$i+=2)
$newData[] = [(string) $year[$i], $cost[$i], $cost[$i+1]];
?>
Now in the javascript portion of the code you just need:
<script>
var newData = <?= json_encode($newData); ?>
</script>
Note that i didnt use the quotes between the php code because i do want the javascript to parse the php output as javascript code and not as a javascript string.
Thanks for all the help. Your answers showed I was going about things the right way (json_encode etc). What has happened though is that the legacy system producing the PHP Arrays was not correcting the values for integers rather than strings. The recipient plug in needed INTs -- see the output array format in the question
So json_encoding the php array worked OK - but it was encoding string rather than INT data values. Fixed that and now it all seems fine.
PS If you look at the orginal question yyou will see the OP array in JS needed two datatypes. And of course it was only getting strings. Lesson there for sure!
Heres the snippet
var a = ['1','2','3'];
var result = a.map(function (x) {
return parseInt(x, 10);
I i try try to access passed php 2d array using json_encode function in javascript it throws the error that its an uncaught typeerror and the array is null, but if i print the contents of array in php only it is printing and having values in it. but it is not passing to javascript.
Both javascript and php are in same file.Below is simply a sample code snippet
var javascript_var = echo json_encode($Php_2D_array);
alert(javascript_var[0].OrderDate[1]); //javascript_var['OrderDate'].[1] earlier i tried to access like this because im having php variable index as a name as mentioned
Please help me sort out this problem
Thanks.
Try this:
var javascript_var = JSON.parse("<?php echo json_encode($Php_2D_array); ?>");
alert(javascript_var[0].OrderDate[1]);
First you need to convert to json and then javascript will take it as string, then you parse it in js.
you can encode array value in javascript by using instruction
JSON.stringify
if your array variable is in php then
var javascript_var = JSON.stringify('<?php echo $Php_2D_array?>');
if your array variable is in javascript
var javascript_var = JSON.stringify(var_array);
I have a a function that returns an array that is structured like this
[[{"title":"Mr","first_name":"James","last_name":"Loo","date_of_birth":36356,"email":"test#test.com","phone_number":1234567890,"company":"CompanyOne"},{"title":"Mr","first_name":"Jonah","last_name":"Lee","date_of_birth":42629,"email":"test#test2.com","phone_number":1234567890,"company":"CompanyTwo"}],
[]]
Within the array are 2 arrays. The first one is a "entry not inserted" array and the second one is a "entry inserted" array.
However when I execute the code through this function
$result = $this->curl->execute();
$result_errors = array();
for($j=0;$j<sizeof($result);$j++){
$result_errors = $result[0];
}
if(sizeof($result_errors)>0){
echo json_encode($result_errors);
}
The result I get in the console is "[" only.
Am I missing something? I have read that I had to echo and json encode arrays but it doesn't seem to be coming out.
if $result is literally as you've printed above, then it's not a PHP array, just a string in JSON format. PHP can't interpret it until you decode it. Your for loop is a waste of time because you always assign the first index of $result to your $result_errors variable. In PHP if you try to fetch an index of a string, you simply get the character which is at that place in the string. The first character of $result is "[".
If you're trying to get the first array out of that response, you need to decode the JSON into a PHP array, select the first inner array, and then re-encode that back to JSON for output, like this:
$array = json_decode($result);
echo json_encode($array[0]);
That will give you the first array, containing the two objects. If that's not the output you're after, then please clarify.
I am not sure you will get what you want but the problem is the assignment to $result_errors. That var should be an array but when you make the assignment $result_errors = $result[0]; your change it from an array to whatever value is at $result[0]; Try this
for($j=0;$j<sizeof($result);$j++){
$result_errors[] = $result[0];
}
My question to you is: Since $result is apparently an array (as indicated by the use of $result[0]) then why not simply do this?
echo json_encode($result);
A suggestion: Instead of sizeof use count.
if(count($result_errors) > 0)
{
echo json_encode($result_errors);
}
count is less likely to be misunderstood by others. It has a totally different meaning in other programming languages.
Oh, and the answer from #ADyson is right to point out the need to decode the json string into a PHP array.
*This question was created as I had no control over the JSON output at the time. So had to use JavaScript. If you have control over the JSON, refer to Mike Brant's answer. But Oka's answer solved my issue below and is a great solution..
I'm trying to create an array that doesn't contain double quotes from JSON.
I'm getting JSON and trying to build a system where I can push non quoted items to the array.
As I have no control over the JSON, I'm making it into a string and removing the double quotes and splitting it into an array again.
The problem is this still outputs the double quotes?
var artistJSON = '<?php echo $favourites ? json_encode($favourites->artists) : '[]' ?>';
var artistIds = artistJSON.replace(/"/g, '');
var artistAry = artistIds.split(',');
console.log(artistJSON);
console.log(artistIds);
console.log(artistAry);
Results from console;
["31","41","56","38","","27"]
[31,41,56,38,,27] //This is a string. I want an array.
["[31", "41", "56", "38", "", "27]"]
https://jsfiddle.net/1pu6nqu2/
Any help would be very grateful.
*Just to confirm, my aim of the game is to remove the double quotes from within the array.
Assuming you're trying to turn stringified JSON into an array, and turn the strings inside the array into numbers. You can use some combination of .map() and .filter() to achieve this.
http://jsbin.com/yojibeguna/1/edit?js,console
var artistJSON = JSON.parse('["31","41","56","38","","27"]')
.map(function (e) { return parseInt(e); })
.filter(function (e) { return isFinite(e); });
console.log(artistJSON, typeof artistJSON[0]);
If you are using json_encode() from PHP to dynamically populate the data structure, you should not populate into a string and then parse that string, just write directly to object/array literal. So change this:
var artistJSON = '<?php echo $favourites ? json_encode($favourites->artists) : '[]' ?>';
to this
var artist = <?php echo $favourites ? json_encode($favourites->artists) : '[]' ?>;
All I did was remove the single quotes (and change the variable name to something more appropriate). Now you have a data structure you can work with directly in javascript without need for additional parsing.
If the json data is stored as JSON data already, you do not need to re-encode it with php. Just echo it out and it will be assigned to your variable artistJSON.
Example:
var artistJSON = <?php echo $favourites ? ($favourites->artists) : '[]' ?>;
Edit: As Mike Brant said, you do need to re-encode it if it's not already stored as JSON literal data (in a db, or whatnot). I'm assuming it is.
Try this:
var artistJSON = '<?php echo $favourites ? json_encode($favourites->artists) : '[]' ?>';
var artists = JSON.parse( artisanJSON );
console.log( artists );
REF: How to json_encode php array but the keys without quotes
You can just run JSON.parse to convert the string to an array.
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
I am generating a JSON string from a PHP array to echo a JS object.
This is what I want to get in js:
var myVar = 123;
//php output:
var obj = {a:1, b:[1,2], c: myVar, d:Date.UTC(2014, 0, 07)}
This is what I have:
<?php
$array = array('a'=>1, 'b'=>array(1,2), 'c'=>???, 'd'=>???);
echo json_encode($array);
?>
The question is: What I put in PHP instead of question marks so that it won't be converted to string?
JSON doesn't support variables or special Date objects. You can only use scalar values (strings, numbers, booleans), arrays and objects (associative arrays).
A way to get what you want would be to return a .js file and have the browser execute that (by including it as a script) instead of transferring simple JSON data. Otherwise you could only define "special" strings that are handled by the receiving side. (For example, array ["var", "myVar"] could be parsed accordingly.)
You could actually do something like that:
<?php
$array = array('a'=>1, 'b'=>array(1,2),
'c'=>'##myVar##',
'd'=>'##Date.UTC(2014, 0, 07)##'
);
$json = json_encode($array);
echo preg_replace('/\"\#\#(.*?)\#\#\"/', '${1}', $json);
?>
But in js JSON.parse won't work, so:
eval("var x = " + json_from_php);
Not such a good idea, but if you need it, it'll work. Just remember not to use this with any "json" which are generated not by your server.