gpt4 book ai didi

php - 为什么 Unpack 函数在 PHP 中返回起始索引为 1 的数组

转载 作者:可可西里 更新时间:2023-11-01 14:03:04 24 4
gpt4 key购买 nike

为什么 PHP 中的 unpack() 函数返回一个从数组索引 1 开始的二进制数据数组。

$str = "PHP";
$binary_data = unpack("C*",$str);
print_r($binary_data);

上述 PHP 脚本打印如下:

数组([1] => 80 [2] => 72 [3] => 80 )

最佳答案

该数组是具有命名键的关联数组,而不是具有数字键的常规数组。这个想法是,您将为每个格式代码命名,结果数组将使用这些名称作为数组键。

例如:

<?php
$str = "PHP";
$binary_data = unpack("C*letter",$str);
print_r($binary_data);

结果:

Array
(
[letter1] => 80
[letter2] => 72
[letter3] => 80
)

来自PHP manual :

The unpacked data is stored in an associative array. To accomplish this you have to name the different format codes and separate them by a slash /. If a repeater argument is present, then each of the array keys will have a sequence number behind the given name.

Example #1 unpack() example

<?php
$binarydata = "\x04\x00\xa0\x00";
$array = unpack("cchars/nint", $binarydata);
?>

The resulting array will contain the entries "chars" with value 4 and "int" with 160.

Example #2 unpack() example with a repeater

<?php
$binarydata = "\x04\x00\xa0\x00";
$array = unpack("c2chars/nint", $binarydata);
?>

The resulting array will contain the entries "chars1", "chars2" and "int".

关于php - 为什么 Unpack 函数在 PHP 中返回起始索引为 1 的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20746655/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com