Pass an array from PHP to JS - javascript

hi i have a big problem i try 3 weaks to solve it but i didn't make anything i have or an errors or i don't take nothing from the results.
i pas an array from query ST_AsGeoJSON from a php code in the javascript code.
there are in the same file html this two codes i get the array from php to javascrypt with this line of code
var jsonAr= <?php echo json_encode($Arresu) ?>;
if i print the jsonAr i receve with document.write(jsonAr); it is give me this format
{ "type":"LineString","coordinates":[[25.9980559326738,39.2420282528175],......,,[26.0486275566016,39.2291388086281]]},{"type":"LineString","coordinates":[[26.0486275566016,39.2291388086281],......[]]}
if i try to take the coordinates and pot it in an array i try this jsonAr.coordinates[0][0] but i did not take any result , i don't know how i take the coordinates

jsonAr.coordinates[0] will give you the first coordinate. jsonAr.coordinates[0][0] only gives you the first number of the first coordinate.

It looks like you want to assign two values to your variable
jsonAr = {...},{...}
Maby you want to try somethig like this:
jsonAr = [{...},{...}]
jsonAr[0].coordinates[0][0] //25.9980559326738
Or
jsonAr = [{...},{...}]
draw_function(jsonAr[0].coordinates[0][0],jsonAr[1].coordinates[0][0]) //25.9980559326738,26.0486275566016

Related

How do I parse part of a JSON object that has mixed string and numbers?

I have a JSON file that was processor generated with lines like this
jsonData: "{data: [350.23,250.32,150.34,340.50,236.70,370.45,380.55]}"
I can target the 'jsonData' object but that returns everything within the double quotes as a string.
I tried ...dataset[0].jsonData[8] which returns the '3' from the first value. I guess I could throw the mixed strings into a JS function and use regex to remove the extra stuff, but thats probably the hackyest way to do this.
Whats the easiest way to target the values only?
If you want to interact with it like the list I would consider something like
var list = jsonData.split("[")[1].split("]")[0].split(",")
Console.log(list);
The console reads:
[
'350.23', '250.32',
'150.34', '340.50',
'236.70', '370.45',
'380.55'
]
From here you can use list[3] to get 340.50
If you don't want to spend the time fixing your JSON just do this:
let values = "{data: [350.23,250.32,150.34,340.50,236.70,370.45,380.55]}".split(',').map(_ => _.replace(/[^0-9.]/g,''))
console.log(values)

PHP Array to JS array and restructure

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);

Codeigniter PHP Ajax returns array brackets only

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.

Javascript/PHP recovering array of arrays

I know this question was answered many times, but I'm still in trouble, due to my confusion on objects, arrays, strings and JSON.
Trying to implement a chart by using Highcharts I made a PHP which extracts data from a DB. Simplifying, let's say that these are just some values pairs (i.e. day,visits).
I want to build an Array of arrays to send to JS.
I made it in this way:
while ($row = mysql_fetch_array($result)) {
$dat = substr($row['data'],8,2); //strip to day
$pag = $row['pagina'];
$data[] = "[".$dat.",".$pag."]";
}
$finalData = join($data, ',');
//echo json_encode($finalData); // I get [09,20],[12,15],[12,11],[12,18]
echo "[".$finalData."]"; //I get [[09,20],[12,15],[12,11],[12,18]]
As you see, I tried two different methods (and some variations with/without json_encode).
On client side, I declared: var donwloaded = [[]]; (array of arrays) which is filled in this way:
....
var response = xmlhttp.responseText;
// donwloaded = JSON.parse(response);
donwloaded = response;
Again I tried in two ways.
With all the possible combination, at the end 'donwloaded' results as a string (according to Mozilla debugger) and the chart is not filled.
The intriguing part is that if in JS I declare this:
var testValues = [ [1,10],[2,20],[3,30],[4,40] ];
which appears similar to what I get from PHP, Mozilla says that this an array of 4 arrays, and Highchart displays it correctly.
I'm sure I did few errors, but after 2 days spent in testing, I'm even more confused.
I did it !
Pls don't ask me how since I'm possibly even more confused than when I started.
I wish to post this message to share the solution for other beginner like myself.
First step was to follow Ruslan Osmanov suggestion:
Replace $data[] = "[".$dat.",".$pag."]"; with $data[] = [$dat, $pag];
Very simple and very effective.
After few attempts (i.e. trying to build a multidimensional array), at the end I just put an echo json_encode($data); and most of the problems were gone.
At the client side, with a simple donwloaded = JSON.parse(response); I finally received what even Mozilla recognizes as an array of arrays, and Highcharts too.
There was still a problem anyway: the values into the arrays were 'stringified' inside double quote, possibly due to the encoding, and Highcarts did not visualized the values.
I changed in PHP the $data with $data[] = [(int)$dat,(int)$pag];
casting the values to number, and now I can finally visualize the chart...great.
Again,I'm almost sure there are more efficient and elegant methods, but it does what I needed and I'm happy.
`

Assigning values to characters in php and javascript

$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).'"' ?>];

Categories

Resources