Laxmi Prasad
Laxmi Prasad

Reputation: 462

json_encode as per keys

For example I have php array as:

$arr = ["a"=>[],"b"=>[]];

for which I need json object as:

{"a":[],"b":{}}

I have huge array for which json_encode function is applied. If I put option as json_encode($data,JSON_FORCE_OBJECT) then it will make every [] object to {} object which is highly undesirable.

Can I apply encode option specific to array keys? Because one should be able to make {"a":[],"b":{}} from php array which is valid json.

Upvotes: 1

Views: 69

Answers (1)

mega6382
mega6382

Reputation: 9396

you can use anonymous classes for this, like(DEMO):

$arr = ["a"=>[],"b"=>new class{}];

This way you can collectively turn some keys into objects and others into arrays.

You can also use the typecast (object), like(DEMO):

$arr = ["a"=>[],"b"=>(object)[]];

I would personally prefer the typecasting method.

Upvotes: 4

Related Questions