gpt4 book ai didi

php - 键中的字符串变成整数?

转载 作者:可可西里 更新时间:2023-10-31 22:47:12 26 4
gpt4 key购买 nike

我为一年中的所有月份编写了一个数组,如下所示:

$MNTH["01"] = "January";
$MNTH["02"] = "February";
$MNTH["03"] = "March";
$MNTH["04"] = "April";
$MNTH["05"] = "May";
$MNTH["06"] = "June";
$MNTH["07"] = "July";
$MNTH["08"] = "August";
$MNTH["09"] = "September";
$MNTH["10"] = "October";
$MNTH["11"] = "November";
$MNTH["12"] = "December";

当我使用 var_dump(array_keys($MNTH))$MNTH 的键进行变量转储时,我得到:

array(12) {
[0]=> string(2) "01"
[1]=> string(2) "02"
[2]=> string(2) "03"
[3]=> string(2) "04"
[4]=> string(2) "05"
[5]=> string(2) "06"
[6]=> string(2) "07"
[7]=> string(2) "08"
[8]=> string(2) "09"
[9]=> int(10)
[10]=> int(11)
[11]=> int(12) }

我期待最后三个键的字符串。怎么变成整数了?我应该怎么做才能纠正这种现象?

最佳答案

PHP 在您创建数组元素时将数字键转换为整数。这不是 array_keys 做的。但是有一个 hack 来获取字符串数字键:

$a = new stdClass;
$a->{"0"} = "zero";
$a = (array) $a;
var_dump($a);

输出:

array(1) {
["0"]=>
string(4) "zero"
}

但是您将无法通过下标访问该 key ,因此它不是很有用。

如果你必须有字符串键,你需要在它们前面加上另一个非数字(或零)字符:

$MNTH["001"] = "January";
$MNTH["012"] = "December";

来自documentation :

A key may be either an integer or a string. If a key is the standard representation of an integer, it will be interpreted as such (i.e. "8" will be interpreted as 8, while "08" will be interpreted as "08"). Floats in key are truncated to integer. The indexed and associative array types are the same type in PHP, which can both contain integer and string indices.

关于php - 键中的字符串变成整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7937150/

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