How would you extract every value of a key regardless of how deep or shallow it is in an array.
Here is a sample JSON array. I want to grab every occurrence of "content" and concatenate them into a single string.
{
"foo": [
"content": "hi",
"inner": []
],
"bar": [
"content": "hi2",
"inner": [
{
"bat": [
"content": "hi3",
"inner": []
],
}
]
]
}
Theoretically that could go on for ever with inner of inner of inner. How do we grab all the content values?
>Solution :
I would use array_walk_recursive() for this, as it is pretty straightforward.
//convert JSON to an array
$data = json_decode($json_data, true);
//create an empty array to hold all of the values we are collecting
$content_values = [];
//this `function` is called for every key in the array that does not contain another array as it's value
//We also pass $content_values as a reference, so we can modify it inside the function
array_walk_recursive($data, function ($value, $key) use (&$content_values) {
if ($key === 'content') {
$content_values[] = $value;
}
});
//Lastly, implode all of the array elements into a string with the given separator
$concatenated_content = implode(', ', $content_values);
echo $concatenated_content;
Output
hi, hi2, hi3