开发者

PHP - retrieve first element of json string without converting to array

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

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

I now want to ge开发者_开发百科t 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?

-----EDIT-----

Thanks for your answers, but what I needed was:

$playedOn = $query -> data -> artist -> services_played_on[0]

(I can't submit this as an answer yet, as I am a 'new' user)


Just decode the JSON first.

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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜