Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the cleanest way to get a checksum of a multidimensional array?

I am doing some sql caching of certain queries. I'm using CakePHP so the query conditions are in an array thus:

array (
  0 => 
  array (
    0 => 'Tutorial.id IN ( SELECT tutorial_id FROM classifications WHERE classifications.product_id = 1 ) ',
  ),
  1 => 
  array (
    'Tutorial.status_id ' => 
    array (
      0 => 4,
      1 => 7,
    ),
  ),
  'OR' => 
  array (
    'Tutorial.user_id' => '40',
  ),
);

I'm mostly looking for the product_id, but there are some other possible conditions, so I wanted to reduce the array to a checksum and append it to the name of the cache file. This way I'd have tutorials_by_classification-413a86af or something, and I wouldn't have to pick thru the array.

I've seen the function to implode mutli-d arrays on php.net in the comments, but I'm wondering if there's a simpler way to achieve my goal.

like image 209
Stop Slandering Monica Cellio Avatar asked Jan 09 '12 22:01

Stop Slandering Monica Cellio


2 Answers

How about serialize and md5? serialize creates a string representation of your array; md5 creates a hash of it.

Example:

$query = array (
  0 => 
  array (
    0 => 'Tutorial.id IN ( SELECT tutorial_id FROM classifications WHERE classifications.product_id = 1 ) ',
  ),
  1 => 
  array (
    'Tutorial.status_id ' => 
    array (
      0 => 4,
      1 => 7,
    ),
  ),
  'OR' => 
  array (
    'Tutorial.user_id' => '40',
  ),
);

$query_string = serialize($query);
$hash = md5($query_string);

echo $query_string, "\n\n\n", $hash, "\n";

/*
a:3:{i:0;a:1:{i:0;s:96:"Tutorial.id IN ( SELECT tutorial_id FROM classifications WHERE classifications.product_id = 1 ) ";}i:1;a:1:{s:19:"Tutorial.status_id ";a:2:{i:0;i:4;i:1;i:7;}}s:2:"OR";a:1:{s:16:"Tutorial.user_id";s:2:"40";}}


a5cb59f0ee259961e426c7ce9b7b8f32
*/
like image 108
lonesomeday Avatar answered Oct 18 '22 16:10

lonesomeday


I would just do this:

$checksum = md5(json_encode($array));

json_encode is slightly faster than serialize, but you lose some of the benefits of serialize. However, for what you're doing, that doesn't matter.

like image 44
Tim Gautier Avatar answered Oct 18 '22 15:10

Tim Gautier