tiswas
tiswas

Reputation: 2101

Retrieve first element of jsonArray string

I have a json string, which I am currently probing as follows:

$playedOn = $query->data->artist->services_played_on

I now want to get the first element of this services_played_on, but am unsure how to do this.. If it were an array I'd just do $query[data][artist][services_played_on][0], but for various reasons this would mess up other code that I have. Anyone have any ideas how I can do this using the -> notation?

Upvotes: 9

Views: 23386

Answers (2)

Christian
Christian

Reputation: 28124

I don't see your problem. If it is JSON, simply deserialize it to PHP as @Marcel said.

If you want the result to be JSON, simply serialize it back.

Example:

$json = '[ {"a":1} , {"d":3} , {"b":2} ]';

$data = json_decode( $json );

$new = json_encode( $data[1] ); // $new is now '{"d":3}'

Since your question is quite ambiguous, I'm not sure if you want the result to be JSON encoded OR whether you want to split the string your own way.

Upvotes: 7

Marcel
Marcel

Reputation: 28087

Just decode the JSON first.

$jset = json_decode($json, true);
echo $jset["data"]["artist"]["services_played_on"][0];

Upvotes: 13

Related Questions