2015-03-31 115 views
1

我需要遍歷PHP中的對象,並對此對象中的每個值應用某個函數。 對象是絕對任意的。它們可以包括變量,另一個對象,數組,對象數組等等......PHP - 遞歸迭代json對象

有沒有一種通用的方法來做到這一點?如果是,如何?

用法示例: 以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": "[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." 
} 
+1

你可以給我們一個例子對象嗎?那肯定會讓它更容易。 – Daan 2015-03-31 10:35:26

+0

對象太長而無法填寫評論框。 :( 基本上,它們非常大,我需要應用一些通用的驗證。 – darxysaq 2015-03-31 10:38:25

+0

如果您在SQL代碼中使用綁定變量,則不需要使用'mysqli_real_escape_string()' – 2015-03-31 10:51:10

回答

0

如果你只需要步行而不需要對數據進行重新編碼,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. 
} 
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');