Drupal PHP序列化和反序列化

3
在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));

我曾经遇到过与这个情况非常相似的问题,反序列化无法正常工作,有些事情对我来说不太清楚,我需要学习一下。请问有人能确认或告诉我问题出在哪里吗?
注:以上代码仅凭记忆编写,可能不准确,因为我目前无法访问它。
1个回答

1
如果我理解正确,您正在将一个数组写入数据库中。
drupal_write_record('prvtmsg_notify', $notify);

应该是:

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

你很可能不再需要它。
$notify['emails'] = serialize($body->emails);

而可以写成:

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

从数据库中检索到数据后,您可以反序列化数组并对其进行迭代,例如:
$array = unserialize(someFunctionToGetPrvtmsg_notifyFromTheDb());
//the array should be the same as the one you serialized

谢谢。$notify数组保存mid、电子邮件以及其他未在代码中显示但将插入多个字段的内容。我会编辑我的问题以使其更清晰。 - Mike
$notify 数组包含除不需要序列化的电子邮件之外的其他内容。 - Mike

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接