简体   繁体   中英

Get property from php object

I did a var dump of a php object $grid , and there is this property that I need to access:

["wpupg_post_types"]=> array(1) { [0]=> string(21) "a:1:{i:0;s:4:"post";}" } 

I need to get the word "post" out of that. I tried doing

$posttype = $grid->wpupg_post_types;
if (in_array("post", $posttype)) {
 echo "post";
}

But that didn't work. And if I try var_dump($grid->wpupg_post_types); it returns NULL.

Do you know how I can do it?

The variable is an array of strings that are serialized:

a:1:{i:0;s:4:"post";}

Pull the first item off and then pass it to unserialize() to turn it into an array:

$result = unserialize(array_shift($grid->wpupg_post_types));

This yields:

Array
(
    [0] => post
)

Note: This assumes the property is public.

$posttype = $grid->wpupg_post_types; contains an array of one element with a serialized array with post.

php > $array = [serialize(['post'])];
php > var_dump($array);
php shell code:1:
array(1) {
  [0] =>
  string(21) "a:1:{i:0;s:4:"post";}"
}

To check if the post is inside the array you need to do another kind of check

php > var_dump(in_array('post', unserialize($array[0])));
php shell code:1:
bool(true)

Your particular case should be

if(in_array('post', unserialize($grid->wpupg_post_types[0]))) {
    echo 'post';
}

EDIT: here my interactive shell

$ php -a
Interactive shell

php > $array = [serialize(['post'])];
php > var_dump($array);
php shell code:1:
array(1) {
  [0] =>
  string(21) "a:1:{i:0;s:4:"post";}"
}
php > var_dump(in_array('post', unserialize($array[0])));
php shell code:1:
bool(true)
php >

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