奇怪的行为 PHP 解压

Strange behavior PHP unpack

帮助了解 PHP 的 unpack.

的工作原理

我知道在 ruby 中我可以以某种方式使用 unpack:

"abcdefgh-abcdefgh-abcdefgh-abcdefgh".unpack("NnnnnN")

=> [1633837924, 25958, 26472, 11617, 25187, 1684366951]

Given the documentation 也在 PHP 中。但实际上它并没有真正起作用。

我需要 6 个元素的数组。让我们试着得到它...

$bytes = openssl_random_pseudo_bytes(16);

var_dump(unpack("NnnnnN", $bytes));

array(1) {
  ["nnnnN"]=>
  int(2679895791)
}

var_dump(unpack("N/n/n/n/n/N", $bytes));

array(1) {
  [1]=>
  int(600384068)
}

var_dump(unpack("N1/n1/n1/n1/n1/N1", $bytes));

array(1) {
  [1]=>
  int(600384068)
}

var_dump(unpack("N1n1n1n1n1N", $bytes));

array(1) {   ["n1n1n1n1N"]=>   int(2679895791) }

我找到了解决方法:

var_dump(array_values(unpack("N1a/n1b/n1c/n1d/n1e/N1f", $bytes)));
array(6) {
  [0]=>
  int(2679895791)
  [1]=>
  int(39295)
  [2]=>
  int(42804)
  [3]=>
  int(32471)
  [4]=>
  int(39559)
  [5]=>
  int(600384068)
}

但我认为有一点黑魔法。请提示如何正确使用 unpack 函数而不使用 aliases(如 N1a)和 array_values

没有。每种格式都会自行评估并覆盖以前的值:

var_dump(unpack("N", $bytes));

array(1) {
  [1]=>
  int(824184250)
}

var_dump(unpack("N/n", $bytes));

array(1) {
  [1]=>
  int(32979)
}

var_dump(unpack("N/n2", $bytes));

array(2) {
  [1]=>
  int(32979)
  [2]=>
  int(48930)
}

它实际上在您链接的文档中:

Caution Be aware that if you do not name an element, an empty string is used. If you do not name more than one element, this means that some data is overwritten as the keys are the same [...]