I can not put element inside JSON

1

I have this JSON ["{\"clube\":[\"Flamengo\"]}"] , and when I run this code:

$clubes = '["{\"clube\":[\"Flamengo\"]}"]';
$clubes = json_decode($clubes, true);
array_push($clubes->clube, 'Santos');
return $clubes;

I have this error as a return

Attempt to modify property of non-object

I wanted to leave JSON like this ["{\"clube\":[\"Flamengo\", "Santos"]}"]

    
asked by anonymous 12.08.2017 / 05:37

2 answers

1

You have converted clubs to array and used object notation within array_push .

$str = '{ "clube":["Flamengo"] }';

$tempArray = json_decode($str, true);
array_push($tempArray['clube'], 'Santos');

print_r($tempArray);
    
12.08.2017 / 05:48
0

The second parameter of the json_decode function defines whether json will be kept as objeto or converted to array , as you passed true then it was defined that it would be used as array , but in line:

array_push($clubes->clube, 'Santos');

You're using objeto notation instead of array :

array_push($clubes['clube'], 'Santos');
    
12.08.2017 / 15:00