1

i have an assoc array which comes from an

mysqli_fetch_assoc() 

function. I would get a value from a random key of it...

Basically, I just need to pick an ICAO up randomly from the db.

So I've found this function

function shuffle_assoc($list) { 
    if (!is_array($list)) return $list; 

    $keys = array_keys($list); 
    shuffle($keys); 
    $random = array(); 
    foreach ($keys as $key) { 
        $random[$key] = $list[$key]; 
    }
 return $random; 
} 

And I tried to code:

$sql = "SELECT icao FROM airport_list";
$result = mysqli_query($conn, $sql);

while ($airports = mysqli_fetch_assoc($result)){
    $random_airport = shuffle_assoc($airports);
}

var_dump($random_airport);

The "var-dumped" result is

array(1) { ["icao"]=> string(4) "ZYTX" }

which seems to be an array that never changes while reloading the page, so... I think it's wrong.

3
  • Are you trying to pull random rows from the table? Commented Oct 3, 2018 at 15:33
  • gyazo.com/3a7aab73448ac12e22282de2a3ad5363 that's the table, i'm trying to get a random 'icao' from all of these. Commented Oct 3, 2018 at 15:35
  • 2
    Can you not just do a ORDER BY RAND() LIMIT 1 and pull that column? Commented Oct 3, 2018 at 15:37

1 Answer 1

3

You can simplify this whole process by pulling a random row from the table by amending your query as can be seen below:

SELECT icao FROM airport_list ORDER BY RAND() LIMIT 1
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.