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>
passing PHP objects to javascript - Stack Overflow
Converting Javascript Object into PHP array - Stack Overflow
How to convert a JavaScript object to a PHP array and get the raw string? - Stack Overflow
php - How can I convert a JavaScript object to an array - Stack Overflow
How can I convert an array back into an object in PHP?
Can I convert an object to an array in PHP while maintaining its methods?
Can I use JSON encoding/decoding for all objects when learning how to convert object to array in PHP?
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
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;
}
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 $key => $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;
Just typecast it
$array = (array) $yourObject;
From Arrays:
If an object is converted to an array, the result is an array whose elements are the object's properties. The keys are the member variable names, with a few notable exceptions: integer properties are unaccessible; private variables have the class name prepended to the variable name; protected variables have a '*' prepended to the variable name. These prepended values have null bytes on either side.
Example: Simple Object
$object = new StdClass;
$object->foo = 1;
$object->bar = 2;
var_dump( (array) $object );
Output:
array(2) {
'foo' => int(1)
'bar' => int(2)
}
Example: Complex Object
class Foo
{
private $foo;
protected $bar;
public $baz;
public function __construct()
{
$this->foo = 1;
$this->bar = 2;
$this->baz = new StdClass;
}
}
var_dump( (array) new Foo );
Output (with \0s edited in for clarity):
array(3) {
'\0Foo\0foo' => int(1)
'\0*\0bar' => int(2)
'baz' => class stdClass#2 (0) {}
}
Output with var_export instead of var_dump:
array (
'' . "\0" . 'Foo' . "\0" . 'foo' => 1,
'' . "\0" . '*' . "\0" . 'bar' => 2,
'baz' =>
stdClass::__set_state(array(
)),
)
To know more about php built-in class stdclass. You can read this documentation
Typecasting this way will not do deep casting of the object graph and you need to apply the null bytes (as explained in the manual quote) to access any non-public attributes. So this works best when casting StdClass objects or objects with only public properties. For quick and dirty (what you asked for) it's fine.
Also see this in-depth blog post:
- Fast PHP Object to Array conversion
You can quickly convert deeply nested objects to associative arrays by relying on the behavior of the JSON encode/decode functions:
$array = json_decode(json_encode($nested_object), true);