随机JSON在PHP中选择项目 [英] Randomly select item from JSON in PHP

查看:221
本文介绍了随机JSON在PHP中选择项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JSON字符串是这样的:

I have a JSON string like this :

[{"Format":"I25","Content":"172284201241"},  {"Format":"I25","Content":"40124139"},
{"Format":"I25","Content":"20197086185689"},
{"Format":"I25","Content":"10215887"},
{"Format":"I25","Content":"702666712272"},
{"Format":"QRCODE","Content":"3"}]

和我只是想选择这些项目中的一个随机,例如:

and I just want to select one of these items randomly,for example :

{"Format":"I25","Content":"40124139"}

我怎样才能做到这一点用PHP?

How can I do this with PHP?

推荐答案

这串看起来很像JSON,所以德code将其放入数组。

That string looks a lot like JSON, so decode it into an array.

$array = json_decode($string, true);

然后,选择一个随机指数:

Then, pick a random index:

$one_item = $array[rand(0, count($array) - 1)];

和最终转换回JSON:

and finally convert back to JSON:

$one_item_string = json_encode($one_item);
echo $one_item_string;

这篇关于随机JSON在PHP中选择项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆