You can use json_encode() to make array as an json object like,
var words = <?php echo json_encode($wordsArray) ?>;// don't use quotes
$.each(words, function(key, value) {
console.log('stuff : ' + key + ", " + value);
});
Answer from Rohan Kumar on Stack OverflowYou can use json_encode() to make array as an json object like,
var words = <?php echo json_encode($wordsArray) ?>;// don't use quotes
$.each(words, function(key, value) {
console.log('stuff : ' + key + ", " + value);
});
For me the simplest way to convert php array to javascript object is to json_encode the php array then JSON.parse it from javascript like this:
<?php
$array = [1 => "one", 2 => "two", 3 => "three"];
?>
<script>
const jsObject = JSON.parse(`<?= json_encode($array) ?>`)
console.log(jsObject) // Object { 1: "one", 2: "two", 3: "three" }
</script>
It seems that your form submits a json object to the server so use json_decode with second parameter set to true to convert it to an array.
$php_array= json_decode($_POST["questionandanswers"],true)
Use json_decode like json_decode($json). It will return an object.
If you want array, use json_decode($json, true).
See: https://www.php.net/manual/en/function.json-decode.php
Converting a php object to javascript array - Stack Overflow
How to convert a JavaScript object to a PHP array and get the raw string? - Stack Overflow
passing PHP objects to javascript - Stack Overflow
PHP array() to javascript array() - Stack Overflow
I'm going to assume that the two arrays you've given for PHP and JS are not related, and they're just examples of how arrays look in the two languages. Clearly you're not going to be able to convert those sequences of letters and numbers into those city names.
PHP provides a function to convert PHP arrays into Javascript code: json_encode(). (technically, it's JSON format; JSON stands for JavaScript Object Notation)
Use it like this:
<script type='text/javascript'>
<?php
$php_array = array('abc','def','ghi');
$js_array = json_encode($php_array);
echo "var javascript_array = ". $js_array . ";\n";
?>
</script>
See also the manual page I linked above for more information.
Note that json_encode() is only available in PHP 5.2 and up, so if you're using an older version, you'll need to use an existing one -- the PHP manual page also includes comments with functions written by people who needed it. (but that said, if you're using anything older than PHP 5.2 you should upgrade ASAP)
Spudley's answer is fine.
Security Notice: The following should not be necessary any longer for you
If you don't have PHP 5.2 you can use something like this:
function js_str($s)
{
return '"' . addcslashes($s, "\0..\37\"\\") . '"';
}
function js_array($array)
{
$temp = array_map('js_str', $array);
return '[' . implode(',', $temp) . ']';
}
echo 'var cities = ', js_array($php_cities_array), ';';
I have fixed the problem. First I converted the object array to a normal array in PHP:
$customers = $app['database']->selectAll('customers');
$allCustomers = array();
foreach($customers as
val)
{
$allCustomers[] = $val;
}
Then in the javascript part, I used json encode on this variable, and used a for loop to add each 'name' property to a javascript array, and finally passed it to the autocomplete function likewise:
var js_data = <?php echo json_encode($allCustomers) ?>;
var customername = [];
for (var i = 0; i < js_data.length; i++)
{
customername[i] = js_data[i]["name"];
}
autocomplete(document.getElementById("customers"), customername);
Thanks a lot everyone for offering your help.
Because you simply need to change the input value instead of the div DOM
document.getElementById("customers").value = customername;
Is this what you are trying to achieve?
$incoming is the jsonString coming from the javascript code
$incoming = '{
"name":"A Name",
"_typography": {
"color": {
"hex":"#2196f3"
},
"text-transform":"uppercase",
"font-weight":"600"
}
}';
$a = json_decode($incoming, true);
echo var_export($a);
RESULT
array (
'name' => 'A Name',
'_typography' =>
array (
'color' =>
array (
'hex' => '#2196f3',
),
'text-transform' => 'uppercase',
'font-weight' => '600',
),
)
Only changes are that you should add true to json_decode and use var_export to get the php array string. If you wanted to get square bracket you could write some custom string generator code.
function convert_js_object_to_php() {
// Getting the JS object
$object = $request->get_header('js_object');
// Decoding it to a PHP object
$output = json_decode($object, true);
if ($output) {
return var_export($output, true);
}
return false;
}
To convert you PHP array to JS , you can do it like this :
var js_array = [<?php echo '"'.implode('","', $disabledDaysRange ).'"' ?>];
or using JSON_ENCODE :
var js_array =<?php echo json_encode($disabledDaysRange );?>;
Example without JSON_ENCODE:
<script type='text/javascript'>
<?php
$php_array = array('abc','def','ghi');
?>
var js_array = [<?php echo '"'.implode('","', $php_array).'"' ?>];
alert(js_array[0]);
</script>
Example with JSON_ENCODE :
<script type='text/javascript'>
<?php
$php_array = array('abc','def','ghi');
?>
var js_array =<?php echo json_encode($disabledDaysRange );?>;
alert(js_array[0]);
</script>
The PHP json_encode function translates the data passed to it to a JSON string which can then be output to a JavaScript variable.The PHP json_encode function returns a string containing the JSON equivalent of the value passed to it.
<?php
$ar = array('apple', 'orange', 'banana', 'strawberry');
echo json_encode($ar); // ["apple","orange","banana","strawberry"]
?>
You can pass the JSON string output by json_encode to a JavaScript variable as follows:
<script type="text/javascript">
// pass PHP variable declared above to JavaScript variable
var ar = <?php echo json_encode($ar) ?>;
</script>
A numerically indexed PHP array is translated to an array literal in the JSON string. A JSON_FORCE_OBJECT option can be used if you want the array to be output as an object instead:
<?php
echo json_encode($ar, JSON_FORCE_OBJECT);
// {"0":"apple","1":"orange","2":"banana","3":"strawberry"}
?>
Associative Array Example:
<?php
$book = array(
"title" => "JavaScript: The Definitive Guide",
"author" => "David Flanagan",
"edition" => 6
);
?>
<script type="text/javascript">
var book = <?php echo json_encode($book, JSON_PRETTY_PRINT) ?>;
/* var book = {
"title": "JavaScript: The Definitive Guide",
"author": "David Flanagan",
"edition": 6
}; */
alert(book.title);
</script>
Notice that PHP's associative array becomes an object literal in JavaScript. We use the JSON_PRETTY_PRINT option as the second argument to json_encode to display the output in a readable format.
You can access object properties using dot syntax, as displayed with the alert included above, or square bracket syntax: book['title'].
here you can find more information and details.
It sounds like you're retrieving a JSON string in JavaScript (perhaps via AJAX?). If you need to make this into an actual array value, you'd probably want to use JSON.parse().
var retrievedJSON = '["float","float","float","float"]'; // normally from AJAX
var myArray = JSON.parse(retrievedJSON);
If you're actually writing out a value into the page, rather than using AJAX, then you should be able to simply echo the output of json_encode directly, without quoting; JSON itself is valid JavaScript.
var myArray = <?php echo json_encode($myPhpArray); ?>;
var myArray = <?= json_encode($myPhpArray); ?>;
Pretty simple. ;-)
Example:
<?php
$myPhpArray = array('foo', 'bar', 'baz');
?>
<script type="text/javascript">
var myJsArray = <?= json_encode($myPhpArray); ?>;
</script>
Should output (view-source):
<script type="javascript">
var myJsArray = ["foo","bar","baz"];
</script>
Example
I found this cool snippet of code that will create a table in JavaScript. I like it because it will allow multiple columns. The onLoad shows how to create the table correctly as I found it.
-
in function havePHPcreateTable()
How do I iterate through the array and remove the quotes on the keys (name:, color:, price:) that was formatted by PHP? -
also in function havePHPcreateTable()
The createTable([]) creates a different type of object than the PHP array, how do I get PHP or reformat it into the correct type of object ?
TestTable.js:
var TBL_NAME = 'tblDIV';
bIsLoaded = false;
cPrev = -1;
window.onload=onLoad;
function onLoad()
{
bIsLoaded = true;
createTable([
{name: 'Banana', price: '3.04', color:'yellow'},
{name: 'Orange', price: '2.56', color:'orange'},
{color:'red', name: 'Apple', price: '1.45'},
{name: 'Cantaloupe', price: '2.45', color:'peach'},
{price: '5.12', name:'Dates', color:'black'}
],
['name', 'price', 'color'], ['Name', 'Price', 'Color']);
havePHPcreateTable();
}
function createTable(objectArray, fields, fieldTitles)
{
if (!bIsLoaded)
return;
let body_table = document.getElementById(TBL_NAME);
let tbl = document.createElement('table');
let thead = document.createElement('thead');
let thr = document.createElement('tr');
var i = 0;
fieldTitles.forEach((fieldTitle) => {
let th = document.createElement('th');
th.appendChild(document.createTextNode(fieldTitle));
const abc = i; // needs const otherwise all i's will be the same
th.onclick=(function(){ sortTable(abc); });
thr.appendChild(th);
i++;
});
thead.appendChild(thr);
tbl.appendChild(thead);
let tbdy = document.createElement('tbody');
let tr = document.createElement('tr');
objectArray.forEach((object) => {
let tr = document.createElement('tr');
fields.forEach((field) => {
var td = document.createElement('td');
td.appendChild(document.createTextNode(object[field]));
td.onclick=(function(){ alert('click '); });
tr.appendChild(td);
});
tbdy.appendChild(tr);
});
tbl.appendChild(tbdy);
body_table.appendChild(tbl)
return tbl;
}
function havePHPcreateTable()
{
var myList = getPHP();
var myListA = myList[0].shift();
var myListB = myList[0].shift();
createTable(myListA, myListB, myListB);
}
function getPHP()
{
myObjB = null;
$.get({
async: false, // need to add a wait for reply statement
url: 'TestTable.php',
success: function(result)
{
if (result !== 'null' && result.length > 1)
{
myObjB = JSON.parse(result);
}
}
});
return myObjB;
}TestTable.php
<?php
function getTable()
{
$name = "apple";
$price = "1.03";
$color = "red";
$abc_item[] = array(
'name:' => $name,
'price:' => $price,
'color:' => $color
);
$abc_list[] = array('name', 'price', 'color');
$abc[] = array($abc_item, $abc_list);
return $abc;
}
echo json_encode(getTable());
?>