PHP从数组中获取随机值有时会返回null

时间:2018-07-14 21:04:55

标签: php

在php的一个数组中,我只有一个索引和数据,例如:

array:1 [
  0 => "{"pk":"4760991153","username":".....","full_name":".....","is_private":true}"
]

在此数组中,我不知道存储了多少数据,并且当我尝试从中获取随机索引以访问该数组的索引时,有时会得到null,例如:

$userPages[]=[
'{"pk":"4760991153","username":".....","full_name":".....","is_private":true}'
];

$data = $userPages[rand(0, count($userPages) - 1)
echo json_decode($data)->pk;

$randomSelectedTag = array_rand($userPages);
$data = $userPages[$randomSelectedTag];
echo json_decode($data)->pk;

输出:

"4760991153",
"4760991153",
"4760991153",
null
"4760991153",
null

我该如何解决此问题,以确保从数组中获取随机数不会返回null?

2 个答案:

答案 0 :(得分:1)

如果您的商品缺少键,请不要使用rand(0, count($userPages) - 1),因为它会计算数组中有多少商品,并返回随机的0-n,而不是实际的按键。

请使用array_rand($userPages)

<?php

$userPages=[
    0 => '{"pk":"1","username":".....","full_name":".....","is_private":true}',
    8 => '{"pk":"2","username":".....","full_name":".....","is_private":true}',
    12 => '{"pk":"3","username":".....","full_name":".....","is_private":true}',
    64 => '{"pk":"4","username":".....","full_name":".....","is_private":true}'
];

for ($i=0; $i < 10; $i++) {
    $data = $userPages[array_rand($userPages)];
    echo json_decode($data)->pk.PHP_EOL;
}

https://3v4l.org/JcQea

或使用array_values()重置密钥,然后您的其他方法将起作用。

https://3v4l.org/2HWcG

答案 1 :(得分:0)

随机索引中没有问题,因为每个随机索引都来自现有的数组范围$data = $userPages[rand(0, count($userPages) - 1)

导致null结果的原因是因为您不检查对象中是否存在pk属性,或者该属性不为null。因此,您应该做简单的检查:

$randomSelectedTag = array_rand($userPages);
$data = $userPages[$randomSelectedTag];
if(isset($data->pk) && !is_null($data->pk)){
   echo json_decode($data)->pk;
}