简体   繁体   中英

How to access attributes of php object inside a array of php objects from javascript

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'])) ?>;

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>

Store php array into javascript variable,

Example Value: (example array inside $_SESSION['objArray'] )

$_SESSION['objArray'] = array(
    'name' => 'foo',
    'email' => 'foo@gmail.com',
    '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":"foo@gmail.com","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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM