This question already has answers here:
Convert php array to Javascript
(21 answers)
Closed 9 years ago.
Iam using PHP,Smarty configuration.
Iam getting an array in PHP and sent it to tpl.I would like to make a javascript array in tpl from that php array.
PHP ARRAY
Array
(
[0] => Array
(
[dt] => 2011-12-02
[number] => 3
)
[1] => Array
(
[dt] => 2011-12-05
[number] => 3
)
[2] => Array
(
[dt] => 2011-12-07
[number] => 2
)
)
and I want to get it as a java script array in tpl
s1 = [[[2011-12-02, 3],[2011-12-05,3],[2011-12-07,2]]];
You'd have to loop through it to generate that array
<script>
var arr = [];
<?php foreach ($arr as $item) : ?>
arr.push(['<?php echo $item['dt']?>', <?php echo $item['number']?>]);
<?php endforeach; ?>
</script>
This will give you an array of arrays.
However, I would do it in another way. I'd just encode it with json and use it as an object
<script>
var data = <?php echo json_encode($arr)?>;
for (var x in data) {
//data[x].dt;
//data[x].number;
}
</script>
I really dislike the idea of inline PHP all over the place. We don't inline JavaScript or CSS these days because it's bad practice i.e. difficult to maintain. We appreciate separation of concerns. If you need to pass data from your application (PHP or otherwise) to JavaScript variables on the client side then there are two good mechanisms you can use. Either get the result as JSON via AJAX, or simply render the variables on the client side in a single accessible location.
Your templating engine should really be able to register the data on the page for you. What you are essentially doing is rendering a script, so your script include mechanism should take an optional argument for registering php variables. If you are not using a templating engine and only need to inject the variables, I guess it would be acceptable to do something along the lines of.
<script type="text/javascript">
var phpdata = <?php echo json_encode($phpdata)?>
</script>
Note that this is declaring a global. We are encouraged to avoid the usage of globals at all costs but I think it's a valid use case when sensibly chosen, such as if you register your own object in global scope as a sensible namespace, then refer to namespace.phpdata. Alternatively you simply wrap your JavaScript in an immediate function call and declare the variable in local scope.
function () {
var phpdata = <?php echo json_encode($phpdata)?>
...
}();
But like I said, in my opinion I think it's better to get your templating engine to handle it, so you pass the PHP data you need for each javascript include, and a single php data object is generated from this data and included in your page.
You can use the php function json_encode to encode the array to json and then use it as an array like object in javascript
First of all: The arrays are not equivalent.
$array = array_map('array_values', $array);
this one is equivalent to the one you want to see as JS-array
$js = json_encode($array);
If you want to keep the keys of the associative (inner) arrays, just omit the first expression.
If you want to do it in the smarty template, loop over your PHP array and output the javascript array elements, adding commas after every element except the last one.
s1 = [
{foreach from=$myArray item=item name=loop}
[{$item['dt']}, {$item['number']}] {if $smarty.foreach.loop.last == false},{/if}
{/foreach}
]
As other said, though - encoding the array as JSON in PHP seems much cleaner and easier way to do that.
first create a new javascript array:
var array = new array();
loop through the php array in your tpl and create the javascript array
foreach($phparray as $i => $ary) {
echo "array[".$i."] = new array(".$ary['dt'].",".$ary['number'].");
}
there are many ways of doing it. I believe there are a lot of solution in the internet.
basically u just need to use for-loops to acheive it
i have already googled it for you.
There
Related
I see many questions about passing an array as a query string in PHP, and it seems the prevailing way is using brackets as in key[]=foo&key[]=bar.
However I cannot find a straight answer about how to send an object (or a key=>value associative array - same thing) as a query string.
Currently, however I do it is:
STRING
?foo=bar&hello=world
Then on the server side, I would do:
<?php
$array = array();
$array['foo']=$_GET['foo'];
$array['hello']=$_GET['hello'];
?>
Of course when using $_POST, this is very simple with an ajax request. Any object you send automatically serializes and isn't a problem.
Is this the best way to handle it, or is there some other standard for sending an object in a query string using PHP?
You can use an associative array in a form and in the query string:
object[foo]=bar&object[hello]=world
To build it URL encoded:
$data['object']['foo'] = 'bar';
$data['object']['hello'] = 'world';
echo http_build_query($data);
Yields:
object%5Bfoo%5D=bar&object%5Bhello%5D=world
You can go many levels and/or use dynamically added elements. In general, in text form, it looks just like a PHP array
object[foo][more][even more][]
Or:
object[foo][][more][even more]
I have text file containing values like this:
varname:
{
varname2: value
varname3:
{
varname4: value
}
}
I need to get this somehow into php array like this:
array(
varname => array
(
varname2 => value
varname3 => array
(
varname4 => value
)
)
)
How can i do this?
I have tried looping through file and trying to make values like that but it gets very tricky when there is multiple level array. Spent many hours without luck...
I suggest you (if you can) to change your file format to a JSON format, that is very similar to your format now:
{"varname":{"varname2":"value","varname3":{"varname4":"value"}}}
Then you can read the file and use json_decode to obtain the array in a very simple form. Here I write the code for decode json to array and echo it:
$s = file_get_contents('datos.js');
$ar = json_decode($s, true);
print_r($ar);
It depends on how much of a hack you want it to be. If you have a true defined format and want to be strict you'd start with a lexer. See http://wezfurlong.org/blog/2006/nov/parser-and-lexer-generators-for-php/ or https://github.com/nikic/Phlexy
On the other hand you could also make it in two steps (depending on how complicated the now shown use cases are).
Replace all leading spaces and replace : \n{ with : { for easier parsing.
Write a recursive parsing function. In every line everything before : is the variable name, everything after the value. If the value is { to a recursion until } and use the result as the value.
I have a PHP script that dumps data from an API.
The dump is an array
print_r($answer);
outputs
Array ( [success] => 1 [serial] => s001 [url] => http://gooole.com )
I want to have another variable called $url that holds the value url from the array (held in $answer) in PHP.
I'm unfamiliar with this.
check out extract() it will take the keys from an array, and create variable of the same name to store them in. There are a few flags you can pass it, to determine exactly what it does with things like pre-existing variables of the same name.
EDIT: as mentioned in the comments on your question, though, $url = $answer['url']; is probably the simplest way to go.
I've created an array from a PHP session variable, and now I'm trying to use ajax (within jQuery) to remove an element from the array.
I've got the following code so far:
$val = $_SESSION['enquiry-basket'];
$array = explode($val);
foreach ($enquiries as $a => $q) {
if ($q == $_POST['product_id']) {
unset($array[$a]);
}
}
The only problem is, it doesn't remove the item.
Can anyone explain why, and tell me how to fix it?
Edit
Sorry guys. The reason I mentioned jQuery is because I use a jQuery ajax call to process the PHP I displayed above.
The ajax query runs fine because it processes some javascript goodies (remove's a div from the HTML) once the ajax returns a success.I've added the delimiter (can't believe I missed it) but the element doesn't get removed from the array still.
I've never been good at multi-dimensional arrays, so here's the array printed:
Array ( [0] => 6 [1] => 8 )
It looks right to me, but I'm an amateur in arrays. (6 and 8 are of course my strings I inserted)
explode is missing the first argument:
explode(',', $val);
You are removing item from $array, not from $_SESSION['enquiry-basket'].
The explode function should have two parameters. But you given only the name of the array.
explode(separator,string,limit);
If I understand correctly what you are trying to do, the problem is that JQuery runs client side, which means that your PHP arrays on the server side disappear between each request from Ajax. The only array that remains is $_SESSION.
If you want to use AJAX, you need to remove from $_SESSION directly. Anything else is just useless because the arrays and variables "disappear" between each call.
Mostly an issue with the explode function, the second parameter is missing:
Change from:
$array = explode($val);
To:
$array = explode('~',$val); // ~ is a delimiter
i want to send a javascript array to php using jquery ajax.
$.post("controllers/ajaxcalls/users.php",
{
links: links
});
where the second 'links' is a javascript array.
when i've got this array:
'1' ...
'1' => "comment1"
'2' => "link1"
'3' => "link2"
'4' => "link3"
'2' ...
'1' => "comment2"
'2' => "link4"
then using:
var jsonLinks = JSON.stringify(links);
alert(jsonLinks);
will give me:
[null,[null,"comment1","link1","link2","link3"],[null,"comment2","link4"]]
seems to me that something is wrong. what are the null:s and i cant use json_decode on php side to get the elements.
what function should i use to convert it to json and how do i access it on the php side?
tried this http://code.google.com/p/jquery-json/ but it will give exactly the same output as JSON.stringify() (they also say that in the documentation).
have struggled with this in some hours now...would appreciate some SPECIFIC help.
i just want to send an array from javascript to php...why is that so damn difficult:/
Answering the null part, JavaScript arrays are numeric and zero based:
>>> var foo = [];
>>> foo[5] = 'Five';
"Five"
>>> foo
[undefined, undefined, undefined, undefined, undefined, "Five"]
On the contrary, PHP allows missing (and mixed) keys:
<?php
$foo = array();
$foo[5] = 'Five';
print_r($foo);
?>
Array
(
[5] => Five
)
If you want to use arrays, I suggest you make them zero-based and prevent missing values. Otherwise, you could probably use objects instead.
There are some jQuery plugin that can encode to JSON (and decode from JSON).
For instance, you can take a look at jquery-json (quoting) :
This plugin exposes four new functions
onto the $, or jQuery object:
toJSON: Serializes a javascript object, number, string, or arry into
JSON.
evalJSON: Converts from JSON to Javascript, quickly, and is trivial.
secureEvalJSON: Converts from JSON to Javascript, but does so while
checking to see if the source is
actually JSON, and not with other
Javascript statements thrown in.
quoteString: Places quotes around a string, and inteligently escapes any
quote, backslash, or control
characters.
I'm not sure how you are trying to read this in your PHP script, but if it is related to you having 1-based arrays rather than 0-based arrays, then in javascript, you can remove the nulls (zeroth element) with:
var jsonLinks = JSON.stringify(links.slice(1));