在PHP中从JSON中随机选择项目


Randomly select item from JSON in PHP

我有一个JSON字符串,像这样:

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

,我只是想随机选择其中一个项目,例如:

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

如何在PHP中做到这一点?

这个字符串看起来很像JSON,所以把它解码成一个数组。

$array = json_decode($string, true);

然后,随机选择一个索引:

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

最后转换回JSON:

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

如果需要将数组元素作为PHP关联数组使用:

$string = '[{"Format":"I25","Content":"172284201241"},  {"Format":"I25","Content":"40124139"},
{"Format":"I25","Content":"20197086185689"},
{"Format":"I25","Content":"10215887"},
{"Format":"I25","Content":"702666712272"},
{"Format":"QRCODE","Content":"3"}]';
$result = array_rand(json_decode($string, true));

如果你想把字符串编码回来:

$result = json_encode(array_rand(json_decode($string, true)));

首先,将json转换为PHP数组,然后从数组中随机选择一个元素:

$json = '[{"Format":"I25","Content":"172284201241"},  {"Format":"I25","Content":"40124139"},
{"Format":"I25","Content":"20197086185689"},
{"Format":"I25","Content":"10215887"},
{"Format":"I25","Content":"702666712272"},
{"Format":"QRCODE","Content":"3"}]';
$arr = json_decode($json, true);
$element = $arr[mt_rand(0, count($arr) - 1)];
// optionally convert back to json
$json = json_encode($element);