0

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!

2
  • 2
    don't use regex, if its a json string, use json_decode. use the proper tool, not regex Commented Jul 22, 2016 at 4:57
  • 1
    Suggest using json_decode Commented Jul 22, 2016 at 5:00

1 Answer 1

1
$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";
}
Sign up to request clarification or add additional context in comments.

8 Comments

This worked, how would I go about getting from the ID based on the username value? Thanks alot.
@JayC You don't need that actually as they are in same index of an array. You can think of property of same object. So when you are accessing id of index 0 you are actually accessing id of the username of object which is in index 0. maybe I didn't understand your question quite well.
I am trying to pull the ID from specific username. All the IDs are unique and so are the usernames (did not have it this way in original post by accident. Have now updated it.) Thanks again @AsifRahaman
@JayC Check my edited answer and let me know if that works for you :)
@AsifRahaman I am getting no response at all, even with error_reporting(E_ALL). Just a blank page. $username will be defined before this script, and will be used to get the ID of that user. If that helps.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.