Why does PHP json_encode flatten array? - javascript

I have this PHP array ($savedRequestDates) of dates:
Array ( [0] => 2018-03-29 10:56:31 [1] => 2018-03-29 10:58:09 [2] => 2018-04-12 11:28:41 [3] => 2018-04-12 13:07:25 [4] => 2018-05-09 13:08:07 )
At the bottom of the same .php page I have this:
<script type="text/javascript">
var sessions = new Array('<?php echo json_encode($savedRequestDates); ?>');
console.log(sessions[0]);
</script>
The console.log(sessions[0]); returns:
["2018-03-29 10:56:31","2018-03-29 10:58:09","2018-04-12 11:28:41","2018-04-12 13:07:25","2018-05-09 13:08:07"]
Why is the JavaScript array flattening at the 0 index? If I try console.log(sessions); it returns an array with one variable, not 5, as the php array clearly shows.
Am I missing something here?

This happens because you're wrapping the array from PHP which another array (new Array). Just remove the new Array part and it will work fine.
var sessions = <?php echo json_encode($savedRequestDates); ?>;

From what I see the call to json_encodewill create a full JSON object and not just the content of the array. You are enclosing the entire output of the PHP generated array as index 0 inside the new Array.
So removing the new Array will generate what you are looking for.
Try this:
<script type="text/javascript">
var sessions = <?php echo json_encode($savedRequestDates); ?>;
console.log(sessions);
</script>
And you should see the entire array.

Related

How do you split a string of pipe separated values and return an array?

I have an array like the following:
array(1) {
[0]=>
string(160) "|ad|al|at|ax|ba|be|bg|by|ch|cz|de|dk|ee|es|eu|fi|fo|fr|gb|gg|gi|gr|hr|hu|ie|im|is|it|je|li|lt|lu|lv|mc|md|me|mk|mt|nl|no|pl|pt|ro|rs|ru|se|si|sj|sk|sm|tr|ua|va|"
}
I'm trying to find a way to strip the pipes and turn them each into an array.
Here's the code that will output the results.
<?php
if( in_array( 'gb', get_field('rights_management_control_by_continent_europe') ) or 'gb' == get_field('rights_management_control_by_continent') ) {
?>
STUFF HERE
<?php } ?>
And just out of curiosity, is this doable in JavaScript?
Use the PHP explode tag.
<?php
$arr = ["|ad|al|at|ax|ba|be|bg|by|ch|cz|de|dk|ee|es|eu|fi|fo|fr|gb|gg|gi|gr|hr|hu|ie|im|is|it|je|li|lt|lu|lv|mc|md|me|mk|mt|nl|no|pl|pt|ro|rs|ru|se|si|sj|sk|sm|tr|ua|va|"];
$pieces = explode("|", $arr[0]);
Each item separated by the pipe symbol would be a new item in the away, with ad being [1] as you start with a pipe.
[ and ] can start and close an array
In Javascript you can split string to array by using
s = "a|b|c"
arr = s.split('|')
//access your array
arr[0]
arr[1]
.....
So you have this array, I'll just put it in a variable $old_array:
$old_array = array(0=>"|ad|al|at|ax|ba|be|bg|by|ch|cz|de|dk|ee|es|eu|fi|fo|fr|gb|gg|gi|gr|hr|hu|ie|im|is|it|je|li|lt|lu|lv|mc|md|me|mk|mt|nl|no|pl|pt|ro|rs|ru|se|si|sj|sk|sm|tr|ua|va|");
To split the string on index 0 we use the explode function on the first element in the $old_array array:
$exploded_array = explode("|", $old_array[0]);
The variable $exploded_array will now hold an array with all the pairs of letters as separate elements:
["","ad","al","at","ax","ba","be",...]
In JavaScript it would look a little different but still similar:
var old_array = ["|ad|al|at|ax|ba|be|bg|by|ch|cz|de|dk|ee|es|eu|fi|fo|fr|gb|gg|gi|gr|hr|hu|ie|im|is|it|je|li|lt|lu|lv|mc|md|me|mk|mt|nl|no|pl|pt|ro|rs|ru|se|si|sj|sk|sm|tr|ua|va|"];
var split_array = old_array[0].split('|');
The split_array variable will contain all the pairs of letters as separate elements:
["","ad","al","at","ax","ba","be",...]

PHP: How do I can decode a json back into array form in Javascript?

I've an array in my php called as $tempoHeader, for example:
Example Array $tempoHeader
-------
Array
(
[0] => red
[1] => green
[2] => yellow
[3] => blue
)
I want to send it into my external javascript, so I do this one in my php code:
My PHP: header.php
$tempoHeader = array_diff_assoc($modelData, $data);
<script type="text/javascript">var header = <?php echo json_encode($tempoHeader); ?>;</script>
<script type="text/javascript" src="upload_header.js"></script>
In my javascript, I've try to console.log(header); and I got this in my console
Array [ "red", "green", "yellow", "blue" ]
My JS: upload_header.js
$(window).load(function() {
console.log(header); //this work and print out the header json
var myObject = JSON.parse(header);
var myArray = jQuery.parseJSON(header);
console.log(myArray); //didn't print out anything
console.log(myObject); //didn't print out anything
});
How do I can decode this json back as $tempoHeader array form?
Note:
I've read this issue jQuery JSON Decode ( PHP to Javascript), and I've try the suggestion such as jQuery.parseJSON(header);, JSON.parse(header); but I got nothing
$res = json_decode( $tempoHeader, true );
echo $res->array_name[index];
I hope this help
The Problem here is that when you executes your JavaScript, your PHP Script was already executed, to "send a variable back to php" you have to create a new Request.
Mostly it is done via Ajax OR you can add your Array in a hidden input field and "send" it with a form.
So you upload_header.js would look like
$(function () {
$.ajax('update_header.php', {
method: 'POST',
data: {
'header': JSON.stringify(header)
}
})
});
and in your "update_header.php" you would recieve the new header with
$newHeader = json_decode($_POST['header'],true);
hope this helps;)
header already is an array, it is not json / a string and you do not need to parse it.
You send this to javascript:
var header = <?php echo json_encode($tempoHeader); ?>;
So you already have an array in javascript as you have noticed:
Array [ "red", "green", "yellow", "blue" ]
And then you try to parse that as json:
var myObject = JSON.parse(header);
That is not possible nor is it necessary: json is a string and JSON.parse() expects a string as its parameter. You cannot use it on an array.
To use your variable, you can simply use header[0] (red), etc. or loop over it like you do with any other javascript array.

Pass php array values as JavaScript array values

I have a PHP array like this.
Array
(
[0] => hal([[br,1],[cl,4]])
[1] => alk([[nc(1),1,2],[nc(1),3]])
)
How to pass to JavaScript like below.
var hal=[["br",1],[cl,4]];
var alk=[[nc(1),1,2],[nc(1),3]];
I write some code
<script>
var data = <?=json_encode($input);?>; //$input is name of the php array
var hal=[data[0].substring(5,data[0].lastIndexOf(']'))];
var alk=[data[1].substring(5,data[1].lastIndexOf(']'))];
document.write(hal[0]);
</script>
The output is [br,1],[cl,1] and my expected output is like the one below.Any ideas? Thank you.
document.write(hal[0]); => ["br",1]
document.write(hal[0][0]); => ["br"]
If you want multiple variables, you'll want to loop through the array; you can grab the names using a regular expression. If you're trying to turn this into valid data you can parse, like a JSON string, you're going to have to do an awful lot of work; likely wherever you're getting this string from would be a better place to look to. Have them pass you a valid JSON string instead.
<script>
<?php foreach($input as $v) {
preg_match("/(\w+)\((.*)\)/", $v, $matches);
$var = $matches[1];
$val = str_replace("'", "\\'", $matches[2]);
echo "var $var = '$val';\n";
} ?>
</script>
There's a package called Transform PHP Vars to JavaScript by Jeffrey Way that you can use to transfer your variable easily to your Javascript.
First, create an implementation of the Laracasts\Utilities\JavaScript\ViewBinder interface. This class is in charge of inserting the given JavaScript into your view/page.
<?php
class MyAppViewBinder implements Laracasts\Utilities\JavaScript\ViewBinder {
// $js will contain your JS-formatted variable initializations
public function bind($js)
{
// Do what you need to do to add this JavaScript to
// the appropriate place in your app.
}
}
Next, put it all together:
$binder = new MyAppViewBinder;
$javascript = new PHPToJavaScriptTransformer($binder, 'window'); // change window to your desired namespace
$javascript->put(['foo' => 'bar']);
Now, you can access window.foo from your JavaScript.
I found an answer for my problem.Here i pass value from php as string.Then that string convert it to an object.
<?php
$input="hal([[br,1],[cl,4]])";
preg_match('#^([^[]+)?([^)]+)#i',$input, $hal); //get string as '[[br,1],[cl,4]]'
?>
<script>
var hal1 = <?=json_encode($hal[2]);?>; //'[[br,1,2],[cl,1,2]]' pass to javaScript
function toJSObject(str){
str = str.replace(/([a-zA-Z]+)/g, '"$1"');
return (JSON.parse(str))
}
var hal = toJSObject(hal1); // pass to JS object [['br',1,2],['cl',1,2]]
document.write(hal);
</script>
And also get this as right.
document.write(hal[0]); => ["br",1]
document.write(hal[0][0]); => ["br"]

Database string value to PHP array to be used in Javascript

I need to store values into a Wordpress database and the use the value in a Google Chart.
The questions are:
1. What format do I use to store it into the database?
Currently I am using WP-TYPES and adding the array as follows to a Multi Line Box:
['Month','Value 1','Value 2'],['2004',1000,400],['2005',1170,460],['2006',660,1120],['2007',1030,540]
This is what it needs to output in the Javascript for the chart.
Convert the String to a array in PHP (Not doing it correctly)
I retrieve the data with:
$graphdata = types_render_field("graph-data", array("output" => "raw","separator"=>";"));
This gives me a string value.
Then I add it to an array:
$thechartcontent[$i] = [
"name" => get_the_title(),
"chartheaders" => array($graphdata),
];
In JavaScipt:
I set the PHP Array to Java
var chart1 = <?php echo json_encode($thechartcontent[0]); ?>;
Then I get the data from the array to a var:
var chartheaders1 = chart1['chartheaders'];
This is where I get stuck. The value that I get is a string. It needs to show exactly this:
['Month','Value 1','Value 2'],['2004',1000,400],['2005',1170,460],['2006',660,1120],['2007',1030,540]
for it to work.
Any help please.
Well, it will not be exacly like you want since it's JSON encoded in JSON format. This might be useful. Or you can convert object into array in JS.
I suspect that what you are outputting is an array containing a string, which is not what you want. You must split $graphdata into an array of arrays containing your data before adding it to $thechartcontent:
$graphdata = substr($graphdata, 1, strlen($graphdata) - 1); // trim the opening and closing brackets
$graphdata = explode('],[', $graphdata); // split $graphdata into an array of strings
foreach($graphdata as &$row) {
$row = explode(',', $row); // split the row into an array
}
$thechartcontent[$i] = array(
'name' => get_the_title(),
'chartheaders' => $graphdata
);
When you json encode the data, you should use the JSON_NUMERIC_CHECK constant, so your numbers don't get quoted as strings:
var chart1 = <?php echo json_encode($thechartcontent[0], JSON_NUMERIC_CHECK); ?>;

Sending array via Ajax fails

var labels = new Array();
<?php foreach($crud_data as $cd ) { ?>
labels['<?php echo $cd['name'] ; ?>'] = '<?php echo $cd['label'] ; ?>';
<?php } ?>
$.post('url.php' , { labels:labels} );
Why can I not send labels array like this? It doesn't show anything in Firebug.
My console.log(labels) result:
[]
avatar
"avatar"
email
"email"
id
"id"
name
"name"
password
"password"
if i populate array like this
<?php foreach($crud_data as $cd ) { ?>
labels.push('<?php echo $cd['label'] ; ?>');
<?php } ?>
$.post('url.php' , { labels:labels} );
it works fine !
Oh I see now. If you have string keys, you have to use an object, not an array:
var labels = {};
Arrays in JavaScript are supposed to only hold elements with numeric keys. While you can assign arbitrary properties to arrays, they are not considered to be elements of the array and thus ignored by most processes which deal with arrays.
Additionally you might want to have a look at jQuery.param to see how jQuery will convert the input to a transport-able string and adjust your data structure accordingly.
labels['<?php echo $cd['name'] ; ?>'] =
It seems you want to create an associative array, which is in fact an object in JavaScript (JavaScript has no dedicated associative arrays). So the array itself is in fact empty because you are adding properties to the array object.

Categories