我需要迭代PHP中的对象并对该对象中的每个单独的值应用某个函数。 对象绝对是任意的。它们可以包括变量,其他对象,数组,对象数组等等......
是否有通用方法可以这样做?如果是,怎么样?
用法示例: RESTful API,以JSON格式接收请求。 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."
}
答案 0 :(得分: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.
}
答案 1 :(得分:0)
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');