I cannot place element inside JSON

Asked

Viewed 51 times

0

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

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

I have as return this error

Attempt to modify property of non-object

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

  • 3

    You converted clubs to array and used object notation within the push array_try array_push($clubes['clube'], 'Santos');

  • That’s what @Rafaelacioly said. You can’t access $clubes->clube, because you want to access a position of a array and not the ownership of an object.

  • Where is this json coming from?

2 answers

1


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

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

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

print_r($tempArray);
  • Use the @Rafaelacioly explanation in your reply, I think it will be clearer to OP what went wrong and your answer will be more interesting.

  • The problem is that it comes from the server with the [] around, I use this way to grab from the server Socios::where('socio', $socio)->pluck('clube');, and this to save $clubes['clube'][0] = $clube;.

  • Then try taking the [0] of $clubs['club'][0] = $club;

  • Inside the database saves right {"clube":["Santos"]}, but when I call he comes [ 
{"clube":["Santos"]}].

  • Look what happens, https://ideone.com/3oazhI so you can’t add item

  • But how can I solve by making the method take the field without the [] ??

  • Laravel I’m still layman, but you already tried to take [0] ? If you don’t try to leave $clubs['club'][0] = $club[0]

  • Is that in fact $clubes['clube'][0] = $clube; I use to save in database, and it saves perfectly {"clube":["Santos"]}, at the time of withdrawal from the bank that comes with the [], ms anyway your answer is right, I will search to arrange it, thank you.

Show 4 more comments

0

The second function parameter json_decode defines whether the json will be maintained as objeto or converted to array, how did you pass true then it was defined that it would be used as array, but on the line:

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

You are using the notation of objeto instead of array:

array_push($clubes['clube'], 'Santos');

Browser other questions tagged

You are not signed in. Login or sign up in order to post.