Reputation: 329
I have an array of php objects. Inside a javascript function I want to access attributes of an object in the array. If I json_encode
the whole array it shows these attributes are undefined
. How can I do this. I new to PHP.
PHP Code:
$_SESSION['objArray'] = $objArray;
Javascript Code:
const objArray = <?php echo json_encode(($_SESSION['objArray'])) ?>;
Upvotes: 3
Views: 125
Reputation: 36134
Store php array into javascript variable,
Example Value: (example array inside $_SESSION['objArray']
)
$_SESSION['objArray'] = array(
'name' => 'foo',
'email' => '[email protected]',
'age' => 30
);
Convert object to array: (optional) (if you have object value inside $_SESSION['objArray']
)
$_SESSION['objArray'] = json_decode(json_encode($_SESSION['objArray']), true);
Solution: (assign in to javascript variable objArray
)
<script>
const objArray = "<?php echo json_encode($_SESSION['objArray']); ?>";
console.log(objArray);
</script>
Console Output:
{"name":"foo","email":"[email protected]","age":30}
Explanation: json_encode
function will convert array in to a json
string and javascript will consider it as a string and at assignment time it need to cover with quotation ether its '
or "
.
Hope this help.
Upvotes: 0
Reputation: 14622
You certainly need to encode your array to JSON so it can be usable by a JavaScript client.
As you mentioned, you have instances of particular classes in your array, so simple JSON encoding won't work for sure.
Here, PHP comes with the JsonSerializable
interface. You will have to implement this interface on your classes. Let's take a Foo
example:
class Foo implements JsonSerializable
{
private $thing;
public function __construct($thing)
{
$this->thing = $thing;
}
public function jsonSerialize()
{
return [
'thing' => $this->thing,
];
}
}
Here is an example of the above code snippet. As you can see, now you can create an instance of Foo
, embed it into an array or whatever, and JSON-encode it with your own representation:
$foo = new Foo('something');
echo json_encode(['foo' => $foo]);
// {"foo": {"thing": "something"}}
Outputting this into an inline JavaScript block would work similar to what you wrote:
<script type="application/javascript">
const obj = "<?php echo json_encode(($_SESSION['objArray'])) ?>;";
</script>
Upvotes: 1