Dealing with deeply-nested arrays

If you have an complex array, you can use data_get() helper function to retrieve a value from a nested array using "dot" notation and wildcard.

1$data = [
2 0 => ['user_id' => 1, 'created_at' => 'timestamp', 'product' => {object Product}],
3 1 => ['user_id' => 2, 'created_at' => 'timestamp', 'product' => {object Product}],
4 2 => etc
5];
6 
7// Now we want to get all products ids. We can do like this:
8 
9data_get($data, '*.product.id');
10 
11// Now we have all products ids [1, 2, 3, 4, 5, etc...]

In the example below, if either request, user or name are missing then you'll get errors.

1$value = $payload['request']['user']['name'];
2 
3// The data_get function accepts a default value, which will be returned if the specified key is not found.
4 
5$value = data_get($payload, 'request.user.name', 'John')

Tip given by @mattkingshott

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 22 courses (477 lessons, total 38 h 20 min)
  • 2 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord