无法将键值对添加到php中的复杂对象

问题描述 投票:-1回答:2

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

$obj= {[email protected]:[usr:130,fname:'Bob',lname:'thekid',news:0,wres:1,SWAGLeaders:0]}

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

这是我到目前为止的内容:

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

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

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

php object key
2个回答
0
投票

首先是将数组分配给对象的相同方法。

$user[0]['email'] = "[email protected]";
$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){[“ [email protected]”] =>数组(3){[0] =>string(9)“元素1”[1] =>string(9)“元素2”[2] =>string(9)“元素3”}}

0
投票

如果您确实需要对象,那么您就走对了路。

$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

© www.soinside.com 2019 - 2024. All rights reserved.