猿问

无法在 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]

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


慕无忌1623718
浏览 151回答 2
2回答

智慧大石

如果你真的需要一个对象,你就走在正确的道路上。$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]=>    string(9) "Element 1"    [1]=>    string(9) "Element 2"    [2]=>    string(9) "Element 3"  }}
随时随地看视频慕课网APP
我要回答