Drupal PHP序列化和反序列化

时间:2013-09-28 21:29:52

标签: php drupal serialization

在Drupal中,我首先序列化出现在私人消息体中的电子邮件,并将其存储为MySQL,如下所示:

function prvtmsg_list($body) {
  $notify = array();
  if (isset($body->emails)) {
    $notify['mid'] = $body->mid;
    $notify['emails'] = serialize($body->emails);
  }
  if (isset($body->vulgar_words) {
    $notify['mid'] = $body->mid;
    $notify['vulgar_words'] = serialize($message->vulgar_words);
  }
  if (isset($notify['mid'])) {
    drupal_write_record('prvtmsg_notify', $notify);
  }
}

当我稍后尝试检索它们时,电子邮件用户化失败,我会像这样检索它们:

function prvtmsg_list_notify() {
  // Select fields from prvtmsg_notify and Drupal pm_message tables
  $query = db_select('prvtmsg_notify', 'n');
  $query->leftJoin('pm_message', 'm', 'n.mid = m.mid');
  $query->fields('n', array('mid', 'emails', 'vulgar_words'));
  $query->fields('m', array('mid', 'author', 'subject', 'body', 'timestamp'));
  orderBy('timestamp', 'DESC');
  $query = $query->extend('PagerDefault')->limit(20);
  $result = $query->execute()->fetchAll();

  $rows = array();
  foreach ($result as $notify) {
    $rows[] = array(
      $notify->author,
      $notify->subject,
      implode(', ', unserialize($notify->emails)),
      implode(', ', unserialize($notify->vulgar_words)),
    );
  }

  $build = array();
  $build['table'] = array(
    '#theme' => 'table',
    '#header' => array(
      t('Author'),
      t('Message subject'),
      t('Emails captured'),
      t('Vulgar Words Captured'),
    ),
    '#rows' => $rows,
  );
  $build['pager']['#theme'] = 'pager';

  return $build;

}

也许我序列化电子邮件的方式有误?这是因为:

dpm(unserialize($notify->emails);

给出Array,Array,Array - 这意味着:

Array( [0] => Array() [1] => Array() [2] => Array() [3] => Array() )

令人惊讶的是,非序列化的低俗词语显示还可以!我不确定是否可以像这样序列化电子邮件:

$notify['emails'] = serialize (array($body->emails));

我遇到了过去的确切情况,其中反序列化对我不起作用,有些事情我不清楚,我需要学习它。任何人都可以确认或告诉我出了什么问题吗?

N.B。上面的代码来自内存,可能不准确,因为我目前无法访问它。

1 个答案:

答案 0 :(得分:1)

如果我正确读取这个,你正在将数组写入db

drupal_write_record('prvtmsg_notify', $notify);

应该是:

drupal_write_record('prvtmsg_notify', serialize($notify));

你很可能不再需要

$notify['emails'] = serialize($body->emails);

而且可以写:

$notify['emails'] = $body->emails;

从db中检索它后,你可以反序列化数组并迭代它:

$array = unserialize(someFunctionToGetPrvtmsg_notifyFromTheDb());
//the array should be the same as the one you serialized