/** * 将一个数组打包成一个Key/Value的消息体 * * @param array $msg * @return string */ public static function toPack($msg) { $content = null; if (is_array($msg) == true) { foreach ($msg as $key => $value) { //这里是个约定,当value为null时,抛弃key. //因此,需要一个空key时候,请将value设置空字符串 if ($value === null) { continue; } //对value是数组的情况进行处理 if (is_array($value) == true) { $value = self::toPack($value); $keyvalue_len = strlen($key) + strlen($value) + 2 + 6; $keyvalue_len = $keyvalue_len | 0x80000000; } else { $keyvalue_len = strlen($key) + strlen($value) + 2 + 6; } $content .= pack("Nn", $keyvalue_len, strlen($key)) . $key . "" . $value . ""; } return $content; } else { if (is_null($msg) == true) { return $content; } else { self::$errno = ERR_PACKAGE_PACK_BAD_PARAM_TYPE; self::$error = '参数应该是null或数组'; return false; } } }