I’m trying to create the follwing object in PHP:
$obj= {abc@gmail.com:[usr:130,fname:'Bob',lname:'thekid',news:0,wres:1,SWAGLeaders:0]}
ultimately $obj will have a number of email addresses each with its own array.
Here’s what I have so far:
$obj = new stdClass(); $obj->{$user[0]['email']}=[];
where $user[0]['email]
contains the email address.
my problem is I don’t know how to add the elements to the array
Advertisement
Answer
You are on the right path if you really need an object.
$user[0]['email'] = 'test'; $obj = new stdClass(); $obj->{$user[0]['email']} = ['usr' => 130, 'fname' => 'Bob', 'lname' => 'thekid', 'news' => 0, 'wres' => 1, 'SWAGLeaders' => 0]; echo json_encode($obj);
Here’s the output. http://sandbox.onlinephpfunctions.com/code/035266a29425193251b74f0757bdd0a3580a31bf
But, I personally don’t see a need for an object, I’d go with an array with a bit simpler syntax.
$user[0]['email'] = 'test'; $obj[$user[0]['email']] = ['usr' => 130, 'fname' => 'Bob', 'lname' => 'thekid', 'news' => 0, 'wres' => 1, 'SWAGLeaders' => 0]; echo json_encode($obj);
http://sandbox.onlinephpfunctions.com/code/13c1b5308907588afc8721c1354f113c641f8788