views:

19

answers:

1

After hours of debugging, I found an error in one of my scripts. For saving different event types in a database, I have an array of unique data for each event that can be used to identify the event.

So I basically have some code like

$key = md5(json_encode($data));

to generate a unique key for each event.

Now, in some cases, a value in the $data array is an integer, sometimes a string (depending on where it comes from - database or URL). That causes the outputs of json_encode() to be different from each other, though - once including quotes, once not.

Does anybody know a way to "unify" the variable types in the $data array? That would probably mean converting all strings that only contain an integer value to integer. Anything else I have to take care of when using json_encode()?

+2  A: 

array_walk_recursive combined with a function you have written to the effect of maybe_intval which performs the conversion you talk about on a single element.

EDIT: having read the documentation for array_walk_recursive more closely you'll actually want to write your own recursive function

function to_json($obj){
  if(is_object($obj))
    $obj=(array)$obj;
  if(is_array($obj))
    return array_map('to_json',$obj);
  return "$obj"; // or return is_int($obj)?intval($obj):$obj; 
}
tobyodavies
I like the edit. I'll report back, thanks.
Franz
Why not `array_walk_recursive`, though?
Franz
Ok, I used `array_map` (recursion isn't needed) with a simple int-to-string conversion function. Thanks for all your help.
Franz
`array_walk_recursive` as far as i can tell won't let you modify the original object or keep track of any nested structure - you can just e.g. print it. If you have no nested structures `array_map` will do
tobyodavies