2

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.

2
  • put the print_r($arr) in your array_random_assoc() to see how your array of arrays that you pass as input looks like Commented Mar 9, 2018 at 6:50
  • This is absolutely correct. If you fetch a random key and insert into a new array, at $key position, your resulting array will have just one position: $key. What you want to achieve is just a normal push, so $r[] = $arr[$keys[$i]]; Commented Mar 9, 2018 at 6:52

1 Answer 1

4

then simply replace this line:

$r[$keys[$i]] = $arr[$keys[$i]];

with

$r[] = $arr[$keys[$i]];

You are getting that format because you have assigned key to array, just need to remove that assignment.

Sign up to request clarification or add additional context in comments.

2 Comments

Beaten to it by a few secs :)
@subhra glad to help you :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.