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?
3
Answers
I would use
array_walk_recursive()
for this, as it is pretty straightforward.Output
You have to create a function that will take the array value. It will check for every array element. If the array element is an array then it will call itself again otherwise the the value will stored in another array.
The new array will be the expected result. For any dimension of the array, it will work.
Here you go:
INPUT:
Recursive Function
Results
You can use ‘implode’ and whatever separator you like. I prefer building an array and then imploding it.
PS. someone already took
array_walk_recursive
– the other answer I believe is incomplete.