In your code there is a problem, you are trying to define an object value for a key within the array directly, this is the reason for your error, in this line:
$jsonData = array("amount" => 500, "payload" => {"duplicateTedAgreement" => false, "favoriteIdTo" => "x" });
Trying to assign an array position to an object "payload" => {}
.
If it is necessary to use this object you can do so by instilling the inner class stdClass
, that is, in practice you define it as an array, but force it to be converted into an object, with (object)
:
$jsonData = array("amount" => 500, "payload" => (object)["duplicateTedAgreement" => false, "favoriteIdTo" => "x"]);
/* RESULTADO */
array(2) {
["amount"]=>
int(500)
["payload"]=>
object(stdClass)#1 (2) {
["duplicateTedAgreement"]=>
bool(false)
["favoriteIdTo"]=>
string(1) "x"
}
}
In the case of the question, as is already done the conversion to json
, it is not necessary to use the (object)
, just set as an array, that itself json_encode
already makes this conversion, staying this way:
$jsonData = array("amount" => 500, "payload" => ["duplicateTedAgreement" => false, "favoriteIdTo" => "x"]);
$jsonDataEncoded = json_encode($jsonData)
/* RESULTADO */
{
"amount": 500,
"payload": {
"duplicateTedAgreement": false,
"favoriteIdTo": "x"
}
}
Credits to Augusto Vasques by comment, had not noticed the json_encode
.
You can’t do that
array("payload" => {"duplicateTedAgreement" => false, "favoriteIdTo" => "x"}});
– Pedro Henrique
You know how I should do ? already tried this way $jsonData = array("amount"=>500,"payload"=>"duplicateTedAgreement"=>false,"favoriteIdTo"=>"x"); however from tbm error
– Rafael