I am working on an API proxy that will accept request, pass it on to a server, and then filter the response such that the requester only receives subset of the response.
Given the following JSON form of response data:
"images": [
{
"id": 2360545,
"src": "https://my_site.com/tester-300x300-1.png",
"name": "tester.png",
},
{
"id": 2433529,
"src": "https://my_site.com/background-01-1.png",
"name": "background.png",
},
]
Using data_get($data, 'images.*.name'); correctly returns an array of the name values
[ 'tester.png', 'background.png' ]
However, in addition to the values, I need also the dotted-string key to each value, in order to data_set() it in a response_to_client array (which starts out empty). i.e. I need a return value of
[
[
'key' => 'images.0.name'
'value' => 'tester.png',
],
[
'key' => 'images.1.name'
'value' => 'background.png'
]
]
Doing
$response_to_client = [];
$names = data_get($data, 'images.*.name');
data_set($response_to_client,'images.*.name',$names);
results in nothing being written to $response_to_client because it has no initial image data.
Doing
$response_to_client = [];
$names = data_get($data, 'images.*.name');
data_set($response_to_client,'images.name',$names);
results in
"images": {
"name": [
"tester.png",
"background.png",
]
}
but I need it to look like
"images": [
{
"name": "tester.png"
},
{
"name": "background.png"
}
]
Need a solution that also works for keys with multiple wildcards. Looked all through the Laravel class and helper functions, nothing seems to give the keys of wildcard matched values.
It's not incorrect at all. You stated yourself that when you do
$namesbecomes['tester.png', 'background.png'].So when you pass
$namestodata_set, it won't magically change to a different format.You'd need to pass an array like this to end up with the format you want.
Which you can get using
array_mapor something similar.https://www.php.net/manual/en/function.array-map