Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

PHP Get the value of every occurrence of a key in a multidimensional array

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading