jeudi 23 juillet 2020

Get random item from JSON array in PHP

I am having trouble getting a random item from the following JSON using

$str = file_get_contents("wisdomquotes.txt"); 
$array = json_decode($str, true); //Fine up to here
$rand = $array[array_rand($array)];//Returns entire array instead of a single random item

Here is JSON:

{
    "quotes": [{
        "keywords": ["work"],
        "quote": " A stich in time saves nine"
    }, {
        "keywords": ["health"],
        "quote": " An apple a day keeps the doctor away."
    }, {
        "keywords": ["money"],
        "quote": " A penny save is a penny earned."
    }, {
        "keywords": ["work"],
        "quote": " You can't burn the candle at both ends."
    }, {
        "keywords": [""],
        "quote": "Tis better to light a candle than to curse the darkness"
    }]
}

What is the correct code to get a random item?




Aucun commentaire:

Enregistrer un commentaire