一个数字字符串作为 PHP 中的数组键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4100488/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 11:57:24  来源:igfitidea点击:

A numeric string as array key in PHP

php

提问by Dogbert

Is it possible to use a numeric string like "123"as a key in a PHP array, without it being converted to an integer?

是否可以将数字字符串"123"用作 PHP 数组中的键,而不将其转换为整数?

$blah = array('123' => 1);
var_dump($blah);

prints

印刷

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

I want

我想要

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

采纳答案by Hamish

No; no it's not:

不; 不,这不对:

From the manual:

手册

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").

键可以是整数或字符串。如果一个键是一个整数的标准表示,它将被解释为这样(即“8”将被解释为 8,而“08”将被解释为“08”)。

Addendum

附录

Because of the comments below, I thought it would be fun to point out that the behaviour is similarbut not identicalto JavaScript object keys.

由于下面的评论,我认为指出该行为JavaScript 对象键相似但不完全相同会很有趣。

foo = { '10' : 'bar' };

foo['10']; // "bar"
foo[10]; // "bar"
foo[012]; // "bar"
foo['012']; // undefined!

回答by David

Yes, it is possible by array-casting an stdClassobject:

是的,可以通过数组转换stdClass对象:

$data =  new stdClass;
$data->{"12"} = 37;
$data = (array) $data;
var_dump( $data );

That gives you (up to PHP version 7.1):

这给了你(直到 PHP 7.1 版):

array(1) {
  ["12"]=>
  int(37)
}

(Update: My original answer showed a more complicated way by using json_decode()and json_encode()which is not necessary.)

(更新:我的原始答案显示了一种更复杂的使用方式json_decode()json_encode()这不是必需的。)

Note the comment: It's unfortunately not possible to reference the value directly: $data['12']will result in a notice.

请注意评论:不幸的是,无法直接引用该值:$data['12']将导致通知。

Update:
From PHP 7.2 on it is also possible to use a numeric string as key to reference the value:

更新
从 PHP 7.2 开始,也可以使用数字字符串作为键来引用值:

var_dump( $data['12'] ); // int 32

回答by steampowered

If you need to use a numeric key in a php data structure, an object will work. And objects preserve order, so you can iterate.

如果您需要在 php 数据结构中使用数字键,则可以使用对象。对象保留顺序,因此您可以迭代。

$obj = new stdClass();
$key = '3';
$obj->$key = 'abc';

回答by Undolog

My workaround is:

我的解决方法是:

$id = 55;
$array = array(
  " $id" => $value
);

The space char (prepend) is a good solution because keep the int conversion:

空格字符(前置)是一个很好的解决方案,因为保持 int 转换:

foreach( $array as $key => $value ) {
  echo $key;
}

You'll see 55 as int.

你会看到 55 是 int。

回答by bcosca

You can typecast the key to a string but it will eventually be converted to an integer due to PHP's loose-typing. See for yourself:

您可以将键类型转换为字符串,但由于 PHP 的松散类型,它最终会转换为整数。你自己看:

$x=array((string)123=>'abc');
var_dump($x);
$x[123]='def';
var_dump($x);

From the PHP manual:

从 PHP 手册:

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.

键可以是整数或字符串。如果一个键是一个整数的标准表示,它将被解释为这样(即“8”将被解释为 8,而“08”将被解释为“08”)。key 中的浮点数被截断为 integer 。索引和关联数组类型在 PHP 中是相同的类型,它们都可以包含整数和字符串索引。

回答by Brainfeeder

I had this problem trying to merge arrays which had both string and integer keys. It was important that the integers would also be handled as string since these were names for input fields (as in shoe sizes etc,..)

我在尝试合并具有字符串和整数键的数组时遇到了这个问题。整数也将作为字符串处理很重要,因为这些是输入字段的名称(如鞋码等)

When I used $data = array_merge($data, $extra);PHP would 're-order' the keys. In an attempt doing the ordering, the integer keys (I tried with 6- '6'- "6"even (string)"6"as keys) got renamed from 0 to n... If you think about it, in most cases this would be the desired behaviour.

当我使用$data = array_merge($data, $extra);PHP 时,会“重新排序”密钥。在尝试进行排序时,整数键(我尝试使用6- '6'-"6"即使(string)"6"作为键)从 0 重命名为n... 如果您考虑一下,在大多数情况下这将是所需的行为。

You can work around this by using $data = $data + $extra;instead. Pretty straight forward, but I didn't think of it at first ^^.

您可以通过使用$data = $data + $extra;来解决此问题。很直接,但我一开始没有想到^^。

回答by TarranJones

Strings containing valid integers will be cast to the integer type. E.g. the key "8" will actually be stored under 8. On the other hand "08" will not be cast, as it isn't a valid decimal integer.

包含有效整数的字符串将被强制转换为整数类型。例如,键“8”实际上将存储在 8 下。另一方面,“08”不会被强制转换,因为它不是一个有效的十进制整数。

WRONG

错误的

I have a casting function which handles sequential to associative array casting,

我有一个处理顺序到关联数组转换的转换函数,

$array_assoc = cast($arr,'array_assoc');

$array_sequential = cast($arr,'array_sequential');

$obj = cast($arr,'object');

$json = cast($arr,'json');



function cast($var, $type){

    $orig_type = gettype($var);

    if($orig_type == 'string'){

        if($type == 'object'){
            $temp = json_decode($var);
        } else if($type == 'array'){
            $temp = json_decode($var, true);
        }
        if(isset($temp) && json_last_error() == JSON_ERROR_NONE){
            return $temp;
        }
    }
    if(@settype($var, $type)){
        return $var;
    }
    switch( $orig_type ) {

        case 'array' :

            if($type == 'array_assoc'){

                $obj = new stdClass;
                foreach($var as $key => $value){
                    $obj->{$key} = $value;
                }
                return (array) $obj;

            } else if($type == 'array_sequential'){

                return array_values($var);

            } else if($type == 'json'){

                return json_encode($var);
            }
        break;
    }
    return null; // or trigger_error
}

回答by GigiManco

As workaround, you can encode PHP array into json object, with JSON_FORCE_OBJECT option.

作为解决方法,您可以使用 JSON_FORCE_OBJECT 选项将 PHP 数组编码为 json 对象。

i.e., This example:

即,这个例子:

     $a = array('foo','bar','baz');
     echo "RESULT: ", json_encode($a, JSON_FORCE_OBJECT);

will result in:

将导致:

     RESULT: {"0" : "foo", "1": "bar", "2" : "baz"}

回答by Nico Schefer

Regarding @david solution, please note that when you try to access the string values in the associative array, the numbers will not work. My guess is that they are casted to integers behind the scenes (when accessing the array) and no value is found. Accessing the values as integers won't work either. But you can use array_shift() to get the values or iterate the array.

关于@david 解决方案,请注意,当您尝试访问关联数组中的字符串值时,数字将不起作用。我的猜测是它们在幕后(访问数组时)被转换为整数并且没有找到任何值。以整数形式访问这些值也不起作用。但是您可以使用 array_shift() 来获取值或迭代数组。

$data = new stdClass;
$data->{"0"} = "Zero";
$data->{"1"} = "One";
$data->{"A"} = "A";
$data->{"B"} = "B";

$data = (array)$data;

var_dump($data);
/*
Note the key "0" is correctly saved as a string:
array(3) {
  ["0"]=>
  string(4) "Zero"
  ["A"]=>
  string(1) "A"
  ["B"]=>
  string(1) "B"
}
*/

//Now let's access the associative array via the values 
//given from var_dump() above:
var_dump($data["0"]); // NULL -> Expected string(1) "0"
var_dump($data[0]); // NULL (as expected)
var_dump($data["1"]); // NULL -> Expected string(1) "1"
var_dump($data[1]); // NULL (as expected)
var_dump($data["A"]); // string(1) "A" (as expected)
var_dump($data["B"]); // string(1) "B" (as expected)

回答by fisharebest

I ran into this problem on an array with both '0' and '' as keys. It meant that I couldn't check my array keys with either == or ===.

我在一个以 '0' 和 '' 作为键的数组上遇到了这个问题。这意味着我无法使用 == 或 === 检查我的数组键。

$array=array(''=>'empty', '0'=>'zero', '1'=>'one');
echo "Test 1\n";
foreach ($array as $key=>$value) {
    if ($key == '') { // Error - wrongly finds '0' as well
        echo "$value\n";
    }
}
echo "Test 2\n";
foreach ($array as $key=>$value) {
    if ($key === '0') { // Error - doesn't find '0'
        echo "$value\n";
    }
}

The workaround is to cast the array keys back to strings before use.

解决方法是在使用前将数组键转换回字符串。

echo "Test 3\n";
foreach ($array as $key=>$value) {
    if ((string)$key == '') { // Cast back to string - fixes problem
        echo "$value\n";
    }
}
echo "Test 4\n";
foreach ($array as $key=>$value) {
    if ((string)$key === '0') { // Cast back to string - fixes problem
        echo "$value\n";
    }
}