Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - recursively iterate over json objects

Tags:

json

object

php

I need to iterate over objects in PHP and to apply a certain function on each and every single value in this object. The objects are absolutely arbitrary. They can include vars, another objects, arrays, arrays of objects and so on...

Is there a generic method to do so? If yes, how?

Usage example: RESTful API which receives requests in JSON format. json_decode() is executed on request body and creates an arbitrary object. Now, it is good, for example, to execute mysqli_real_escape_string() on every value in this object before further validations.

OBJECT EXAMPLE:

{
  "_id": "551a78c500eed4fa853870fc",
  "index": 0,
  "guid": "f35a0b22-05b3-4f07-a3b5-1a319a663200",
  "isActive": false,
  "balance": "$3,312.76",
  "age": 33,
  "name": "Wolf Oconnor",
  "gender": "male",
  "company": "CHORIZON",
  "email": "[email protected]",
  "phone": "+1 (958) 479-2837",
  "address": "696 Moore Street, Coaldale, Kansas, 9597",
  "registered": "2015-01-20T03:39:28 -02:00",
  "latitude": 15.764928,
  "longitude": -125.084813,
  "tags": [
    "id",
    "nulla",
    "tempor",
    "do",
    "nulla",
    "laboris",
    "consequat"
  ],
  "friends": [
    {
      "id": 0,
      "name": "Casey Dominguez"
    },
    {
      "id": 1,
      "name": "Morton Rich"
    },
    {
      "id": 2,
      "name": "Marla Parsons"
    }
  ],
  "greeting": "Hello, Wolf Oconnor! You have 3 unread messages."
}
like image 847
darxysaq Avatar asked Mar 26 '26 14:03

darxysaq


1 Answers

If you just need to walk over the data and won't need to re-encode it, json_decode()'s second parameter, $assoc will cause it to return an associative array. From there, array_walk_recursive() should work well for what you're after.

$data = json_decode($source_object);
$success = array_walk_recursive($data, "my_validate");

function my_validate($value, $key){
    //Do validation.
}
like image 183
Red Avatar answered Mar 28 '26 04:03

Red