I was trying to pick one random data from JSON array using PHP but the wrong format is coming after getting result. I am explaining the code below.
<?php
function array_random_assoc($arr, $num = 1) {
$keys = array_keys($arr);
shuffle($keys);
$r = array();
for ($i = 0; $i < $num; $i++) {
$r[$keys[$i]] = $arr[$keys[$i]];
}
return $r;
}
$arr=array(array("id"=>2,"title"=>"hello"),array("id"=>3,"title"=>"hel"),array("id"=>4,"title"=>"hell"),array("id"=>5,"title"=>"helloddd"));
$result=array_random_assoc($arr);
echo json_encode($result);
//print_r(array_random_assoc($arr));
?>
Here I am getting the below type result.
{"2":{"id":4,"title":"hell"}}
Here my requirement is one random set of data will pick from the existing array and the expected output should like below.
[{"id":4,"title":"hell"}]
for each time of function call the value will be picked randomly from that array.
print_r($arr)in yourarray_random_assoc()to see how your array of arrays that you pass as input looks like$keyposition, your resulting array will have just one position:$key. What you want to achieve is just a normal push, so$r[] = $arr[$keys[$i]];