问题
I have a class that is receiving API data and I would like to wrap all of the responses into a collection class. So, I receive the data from the API call, turn it into a plain associative php array, and wrap it using the collect()
helper.
I was half expecting it to work just like Eloquent does where you can reference a key as a collection property, but it doesn't.
Here is an example of response data I would receive:
$data = [
'status' => 'SUCCESS',
'message' => 'Your request was received.',
'data' => [
'first_name' => 'John',
'last_name' => 'Doe',
'address' => [
'street' => '123 Main St.',
'city' => 'Any City',
'state' => 'TX',
'zip' => '12345',
'country' => 'USA'
],
'email' => 'john@doe.com',
'phone' => '(123) 456-7890',
'role' => 'Administrator',
'active_orders' => 3
]
];
$response = collect($data);
I would like to be able to wrap this data in a collection and use it like so:
$response->data->address->street
or $response->data->first_name
However, I get an error that says Property [data] does not exist on this collection instance.
I have to refer to it like an array if I want to access it. E.g. $response['data']['first_name']
. If I wanted to use that syntax I would just keep it as an array.
How can I recursively set my collection properties as the array key names so I can use it much like I would an Eloquent query?
回答1:
How can I recursively set my collection properties as the array key names so I can use it much like I would an Eloquent query?
json_decode()
normally deconstructs into such an object. But you need to start with JSON. So, it seems silly, and it's probably not terribly efficient, but this should do what you want:
$response = json_decode(json_encode($data));
来源:https://stackoverflow.com/questions/46221804/make-associative-array-into-a-collection-similar-to-eloquent-query-collection