无法在 PHP 中向复杂对象添加键值对



我正在尝试在PHP中创建以下对象:

$obj= {abc@gmail.com:[usr:130,fname:'Bob',lname:'thekid',news:0,wres:1,SWAGLeaders:0]}

最终$obj将有许多电子邮件地址,每个电子邮件地址都有自己的数组。

这是我到目前为止所拥有的:

$obj = new stdClass();
$obj->{$user[0]['email']}=[];

其中$user[0]['email]包含电子邮件地址。

我的问题是我不知道如何将元素添加到数组中

如果你真的需要一个对象,你就走在正确的道路上。

$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);

这是输出。 http://sandbox.onlinephpfunctions.com/code/035266a29425193251b74f0757bdd0a3580a31bf

但是,我个人认为不需要对象,我会使用语法更简单的数组。

$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

与最初将数组分配给对象的方式相同。

$user[0]['email'] = "abc@gmail.com";
$obj = new stdClass;
$obj->{$user[0]['email']} = [];
$obj->{$user[0]['email']}[] = "Element 1";
$obj->{$user[0]['email']}[] = "Element 2";
$obj->{$user[0]['email']}[] = "Element 3";
var_dump($obj);
object(stdClass(#1 (1( { ["abc@gmail.com"]=>array(3( { [0]=>字符串(9( "元素 1" [1]=>字符串(9( "元素 2" [2]=>字符串(9( "元素 3" } }

最新更新