【问题标题】:PHP - recursively iterate over json objectsPHP - 递归迭代 json 对象
【发布时间】:2015-06-04 16:06:16
【问题描述】:

我需要遍历 PHP 中的对象,并在该对象中的每个值上应用某个函数。 对象是绝对任意的。它们可以包括变量、另一个对象、数组、对象数组等等......

有通用的方法吗?如果是,怎么做?

使用示例: 以 JSON 格式接收请求的 RESTful API。 json_decode() 在请求主体上执行并创建一个任意对象。 现在,例如,在进一步验证之前对该对象中的每个值执行 mysqli_real_escape_string() 是很好的。

对象示例:

{
  "_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": "wolfoconnor@chorizon.com",
  "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."
}

【问题讨论】:

  • 你能给我们一个例子吗?这肯定会让事情变得更容易。
  • 对象太长,无法填写评论框。 :( 基本上,它们非常大,我需要应用一些通用验证。
  • 如果您在 SQL 代码中使用绑定变量,则无需使用 mysqli_real_escape_string()

标签: php json object


【解决方案1】:

如果您只需要遍历数据而不需要重新编码,json_decode() 的第二个参数$assoc 将导致它返回一个关联数组。从那里开始,array_walk_recursive() 应该可以很好地满足您的需求。

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

function my_validate($value, $key){
    //Do validation.
}

【讨论】:

    【解决方案2】:
    function RecursiveStuff($value, $callable) 
    {
       if (is_array($value) || is_object($value)) 
       {
           foreach (&$prop in $value) {
              $prop = RecursiveStuff($prop);
           }
       } 
       else {
           $value = call_user_func($callable, $value);
       }
       return $value;
    }
    

    并像这样使用它:

    $decodedObject = RecursiveStuff($decodedObject, function($value) 
    {
       return escapesomething($value); // do something with value here
    });
    

    你可以像这样传递函数名:

    $decodedObject = RecursiveStuff($decodedObject, 'mysqli_real_escape_string');
    

    【讨论】:

    • 您遇到了错误,应该是:...foreach ($value as &$prop) { $prop = RecursiveStuff($prop, $callable);...
    猜你喜欢
    • 1970-01-01
    • 2011-01-13
    • 1970-01-01
    • 1970-01-01
    • 2019-10-26
    • 2015-01-14
    • 1970-01-01
    • 1970-01-01
    • 2013-12-01
    相关资源
    最近更新 更多