Jay C
Jay C

Reputation: 21

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": "[email protected]", "status": on},{"id": "afadfatqwertqr", "username": "test2", "type": "1", "email": "[email protected]", "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!

Upvotes: 0

Views: 1419

Answers (1)

Asif Rahaman
Asif Rahaman

Reputation: 775

$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:

if(isset($username[$usernameToFind])){
    $idToFind = $username[$usernameToFind];
}else{
    echo "this user doesn't exist";
}

Upvotes: 1

Related Questions