0
$api_url = 'https://catfact.ninja/facts';

$json_data = file_get_contents($api_url);

$response_data = json_decode($json_data);

$users = $response_data->data;

var_dump($users);

i want to foreach the users and echo each one how can i do that?

this is the result of var_dump($users)

array(10) { [0]=> object(stdClass)#2 (2) { ["fact"]=> string(114) "Unlike dogs, cats do not have a sweet tooth. Scientists believe this is due to a mutation in a key taste receptor." ["length"]=> int(114) } [1]=> object(stdClass)#3 (2) { ["fact"]=> string(97) "When a cat chases its prey, it keeps its head level. Dogs and humans bob their heads up and down." ["length"]=> int(97) } [2]=> object(stdClass)#4 (2) { ["fact"]=> string(60) "The technical term for a cat’s hairball is a “bezoar.”" ["length"]=> int(54) } [3]=> object(stdClass)#5 (2) { ["fact"]=> string(42) "A group of cats is called a “clowder.”" ["length"]=> int(38) } [4]=> object(stdClass)#6 (2) { ["fact"]=> string(146) "A cat can’t climb head first down a tree because every claw on a cat’s paw points the same way. To get down from a tree, a cat must back down." ["length"]=> int(142) } [5]=> object(stdClass)#7 (2) { ["fact"]=> string(62) "Cats make about 100 different sounds. Dogs make only about 10." ["length"]=> int(62) } [6]=> object(stdClass)#8 (2) { ["fact"]=> string(55) "Every year, nearly four million cats are eaten in Asia." ["length"]=> int(55) } [7]=> object(stdClass)#9 (2) { ["fact"]=> string(100) "There are more than 500 million domestic cats in the world, with approximately 40 recognized breeds." ["length"]=> int(100) } [8]=> object(stdClass)#10 (2) { ["fact"]=> string(43) "Approximately 24 cat skins can make a coat." ["length"]=> int(43) } [9]=> object(stdClass)#11 (2) { ["fact"]=> string(278) "While it is commonly thought that the ancient Egyptians were the first to domesticate cats, the oldest known pet cat was recently found in a 9,500-year-old grave on the Mediterranean island of Cyprus. This grave predates early Egyptian art depicting cats by 4,000 years or more." ["length"]=> int(278) } }

  • 1
    Add **true** to json decode and it will turn the object into an associated array **json_decode($json_data,true)** that you can loop through – imvain2 Jul 06 '22 at 16:41
  • Always use `true` as the second argument of [`json_decode()`](https://www.php.net/manual/en/function.json-decode). It decodes the objects encoded in JSON as PHP arrays (by default it decodes them to PHP anonymous objects). PHP arrays are much easier to handle than objects. – axiac Jul 06 '22 at 16:42
  • thank you i manage to display it now! – jhayvon brutal Jul 06 '22 at 16:49

0 Answers0