简体   繁体   中英

Laravel and JSON response

I have JSON response that looks like this:

{
    "success": true,
    "ownersList": [
       { "propertiesList": [],
         "email": "email@email.com"  },
       { "propertiesList": [],
         "email": "email2@email.com" }
    ]
}

How do I grab all of the propertiesList associated with a specific "email" value?

I don't think you need anything fancy from Laravel to do this. You will probably want to use Guzzle (which is a Laravel dependency) since it's nice and easy CURL wrapper for PHP.

// assumes the API response is in variable $api_response_body_as_a_string
$o_api_response = json_decode($api_response_body_as_a_string);
$owners_list = $o_api_response->owners_list;
$propertiesList = NULL;
foreach($owners_list as $this_owner) {
    if('email@to.find' === $this_owner->email) {
        $propertiesList = $this_owner->$propertiesList;
        break;
    }
}
// $propertiesList has the result or is NULL

Original question (before OP clarification):

You currently don't have any code related to Laravel in your question, so I'll venture a guess that you are querying a table where propertiesList is a foreign key of the ownersList Model: http://laravel.com/docs/eloquent#eager-loading

Otherwise, more information about your setup (models and relationships) will be necessary to help you.

You may try something like this:

$obj = json_decode($json);
$item = null;
array_walk($obj->ownersList, function($i) use (&$item) {
    if($i->email == 'email@email.com') $item = $i;
});

// Print out the item
dd($item);

I've used hard coded 'email@email.com' , you may use a variable or whatever thing you have.

I realise the question is quite old and has been answered, but a nice clean way with Laravel is to do something like:

$json = json_decode($response, true);

$properties = collect($json['ownersList'])
    ->where('email', 'email@email.com')
    ->pluck('propertiesList')->all();

Internally, this does similar things to the other questions, but it is much more fluent and easier to read and understand.

See the Collection documentation for more information.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM