2 回答

TA貢獻1946條經驗 獲得超3個贊
如果你真的需要一個對象,你就走在正確的道路上。
$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

TA貢獻1818條經驗 獲得超3個贊
與最初將數組分配給對象的方式相同。
$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]"]=>
array(3) {
[0]=>
string(9) "Element 1"
[1]=>
string(9) "Element 2"
[2]=>
string(9) "Element 3"
}
}
- 2 回答
- 0 關注
- 132 瀏覽
添加回答
舉報