Jay C Jay C - 3 months ago 7
PHP Question

Getting specific data from JSON array. [PHP]

I have a script that pulls data from an external API. The output example is below.

[{"id": "579144bbfbd8f54f53f5394b", "username": "test1", "type": "1", "email": "new_user@email.com", "status": on},{"id": "afadfatqwertqr", "username": "test2", "type": "1", "email": "new_user2@email.com", "status": on}]

I am trying to pull the id solely from the string to set it as a variable. It has to be username specific as well but any support would be greatly appreciated. Been racking my head, thanks in advance!

$usernameToFind = 'something';  

Then you need to call your api get JSONResponse;

$arr = json_decode($yourJSON, true);

then your $arr will contain all data as array of object. and you can access as below:

$username = array();

$len = count($arr);
for($i = 0; $i < $len; $i++){
    $id = $arr[$i]["id"];
    $uname = $arr[$i]["username"];
    $username[$uname] = $id;

After this loop you can get whatever id you want to find based on username given that usernameToFind exist in that array. To check that you can use:

    $idToFind = $username[$usernameToFind];
    echo "this user doesn't exist";