0

有谁知道如何将此函数从 Python 转换为 PHP?

我一直在使用它,但是 Python 代码中有一些我无法弄清楚的东西。

此函数用于以下上下文: http ://www.dmcloud.net/doc/api/general.html#authentication

def normalize(input=None):
output = ''

if type(input) in (list, tuple):
    for element in input:
        if type(element) in (dict, list, tuple):
            element = normalize(element)
        output += str(element)

elif type(input) is dict:
    keys = input.keys()
    keys.sort()
    for key in keys:
        element = input[key]
        if type(element) in (dict, list, tuple):
            element = normalize(element)
        output += '%s%s' % (key, element)

else:
    output = str(input)

return output

谢谢!

4

1 回答 1

2

php 在字典和元组/列表之间没有区别,所以:

function normalize($input=null) {
  if (! is_array($input)) {
    return strval($input);
  }

  $res = '';
  $keys = array_keys($input);
  sort($keys);
  foreach ($keys as $k) {
    if (!is_int($k)) $res .= $k;
    $res .= normalize($v);
  }
  return $res;
}

值得注意的是,这种序列化很糟糕,因为它无法区分整数和数字。你真的应该使用 JSON(在phpPython中),它是一种独立于语言的、人类可读的序列化格式。

与其使用此字符串进行身份验证,不如简单地使用JSON 序列化的散列。

于 2011-10-28T21:53:07.187 回答