N
N
newaitix2015-10-22 13:01:14
PHP
newaitix, 2015-10-22 13:01:14

Convert php object to javascript object?

Tell me how to do it. The problem is simple but not solved.
There is a php object.

<?
$vi = array(
'a'=>1,
'b'=>2
);
?>

You need to get this object in javascript
in the following form, respectively
var vi = {
a:1,
b:2
};

I complicate the task a little by the fact that all this scale is in the heredoc
<?
echo<<<heredoc
<script>
var vi = {
a:1,
b:2
};
</script>
heredoc;

Answer the question

In order to leave comments, you need to log in

2 answer(s)
K
kapuletti, 2015-10-22
@kapuletti

php.net/manual/en/function.json-encode.php

M
Michael, 2015-10-22
@scherbuk

<?php 
$vi = array(
'a'=>1,
'b'=>2
);
foreach ($vi as $key => $value) {
    $result[] = $key . ':' . $value;
}
$result = implode(",\n", $result);
?>
<script>
var vi = {
<?=$result?>

}
</script>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question