0

Hey i'm currently trying to get randomuser.me's api to work so that i can get users from there and put them into my Mysql Table ´users´ but some how i can't make it happen. And then hows the best way to put it into the mysql i know i can just place it in the foreach but maybe there is better ways?

I've tried to put it in a foreach but i always end up with the results*:

gender = female
name = Array
location = Array (*how to i get the json under location?) 
email = francesca.ozturk@example.com
login = Array
dob = Array
registered = Array 
phone = 0906-4547969
cell = 0172-3081101
id = Array
picture = Array
nat = DE

I use this as code currently

 <?php

$user = json_decode(file_get_contents('https://randomuser.me/api/? 
results=20&gender=female&nat=de'), true);



    foreach($user as $key => $arrays){
    foreach($arrays as $array){
        foreach($array as $key => $value ){
            echo $key . " = " . $value . "<br />";
        }
        echo "<br />";
    }
    echo "<br />";
}

?>
jonas
  • 17
  • 5

1 Answers1

1

You can use something like this:

<?php

$user = json_decode(
    file_get_contents(
        'https://randomuser.me/api/?results=20&gender=female&nat=de'
), 
true);

function printArray( $entryKey, $entry ){

    if ( gettype( $entry ) != "array" ){
        echo $entryKey . " = " . $entry . "<br />";
    } else {
        foreach ( $entry as $key => $value ){
            if ( gettype( $value) == "array" ){
                printArray( $entryKey, $value );
            }

            // 1) Do not display parent key:
            // echo $key . " = " . $value . "<br />";

            // 2) Display parent key:
            echo $entryKey . "." . $key . " = " . $value . "<br />";
        }
    }

}

foreach( $user['results'] as $key => $arrays ){
    foreach( $arrays as $innerkey => $innervalue ){
        printArray( $innerkey, $innervalue );
    }
    echo "<br>";
}

?>

You can try case 1) or 2), and have the result properties displayed along with the parent key or without.

For MySQL insertion of multiple rows, you can check out this post: insert multiple rows via a php array into mysql

Kostas Minaidis
  • 4,681
  • 3
  • 17
  • 25