【问题标题】:Drupal PHP serialize and unserializeDrupal PHP 序列化和反序列化
【发布时间】:2013-09-28 21:29:52
【问题描述】:

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

我在过去遇到了反序列化对我不起作用的确切情况,有些东西我不清楚,我需要学习它。谁能确认或告诉我出了什么问题?

注意以上代码来自记忆,可能不准确,因为我目前无权访问它。

【问题讨论】:

    标签: php drupal serialization


    【解决方案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 数组包含中间件、电子邮件以及代码中未显示的其他内容,这些内容将插入多个字段。我将编辑我的问题以使其清楚。
    • $notify 数组包含不需要序列化的电子邮件以外的其他内容。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-02
    • 1970-01-01
    • 2012-03-17
    相关资源
    最近更新 更多