/    Sign up×
Community /Pin to ProfileBookmark

List of Objects into JSON

I’ve got an array of objects. I want to make this a JSON array.

I thought

$json = json_encode($MyList->getPeople());

would work but I json object is empty.

to post a comment
PHP

5 Comments(s)

Copy linkTweet thisAlerts:
@kiwisauthorDec 14.2020 — Okay, so If I make my object properties public it works fine.

When they're private it returns empty.

Any ideas?
Copy linkTweet thisAlerts:
@VITSUSADec 14.2020 — What is the main objective? After that, we can suggest to you about JSON array.
Copy linkTweet thisAlerts:
@NogDogDec 14.2020 — __(The following does not really address your question, please see my later reply. :) )__

Create a public method that returns the property of interest.
<i>
</i>class Foo
private $bar = [1, 2, 3];
public function bar() {
return $this-&gt;bar;
}
}

$foo = new Foo();
$foo_json = json_encode($foo-&gt;bar());
Copy linkTweet thisAlerts:
@kiwisauthorDec 14.2020 — I've found these articles

https://stackoverflow.com/questions/34710347/json-encode-an-array-of-objects-with-private-properties?lq=1

https://stackoverflow.com/questions/7005860/php-json-encode-class-private-members
Copy linkTweet thisAlerts:
@NogDogDec 14.2020 — > @kiwis80#1625867 I've got an array of objects.

Oh, sorry, I missed that part. I thought it was just a private/public issue. Sounds like that JsonSerializable interface is probably the way to go.
×

Success!

Help @kiwis spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 4.26,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...