本文介绍了不能使用数字键作为字符串的 PHP 数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 PHP 数组,它有一个字符串类型的数字键.

但是当我尝试访问它们时,PHP 给了我一个未定义的索引错误.

$a = (array)json_decode('{"1":1,"2":2}');var_dump($a);var_dump(isset($a[1]));var_dump(isset($a["1"]));var_dump($a[1]);var_dump($a["1"]);

输出:

数组(大小=2)'1' => 整数 1'2' => 整数 2布尔假布尔假错误:E_NOTICE:未定义的偏移量:1空值错误:E_NOTICE:未定义的偏移量:1空值

如何访问这些值?

演示:http://codepad.viper-7.com/8O03IM

解决方案

所以,我还没有看到任何其他答案涉及这个,但 @xdazz 接近了.

让我们开始我们的环境,$obj 等于解码字符串的对象符号:

php >$obj = json_decode('{"1":1,"2":2}');php >打印_r($obj);标准类对象([1] =>1[2] =>2)php >var_dump( $obj );对象(标准类)#1(2){[1"]=>整数(1)[2"]=>整数(2)}

如果您想访问字符串,我们知道以下操作会失败:

php >回声 $obj->1;解析错误:解析错误,在第 1 行的 php shell 代码中需要T_STRING"或T_VARIABLE"或{"或$"

访问对象变量

您可以像这样访问它:

php >回声 $obj->{1};1

这就是说:

php >回声 $obj->{'1'};1

访问数组变量

数组的问题是以下返回空白,这是类型转换的问题.

php >回声 $obj[1];php >

如果您将其回退,该对象将再次可访问:

php >$obj = (对象) $obj;php >回声 $obj->{1};1

这是一个可以为您自动执行上述操作的功能:

function array_key($array, $key){$obj = (object) $array;返回 $obj->{$key};}

示例用法:

php >$obj = (数组) $obj;php >echo array_key($obj, 1);1php >echo array_key($obj, 2);2

I have a PHP array that has numeric keys as a string type.

But when I try and access them PHP is giving me an undefined index error.

$a = (array)json_decode('{"1":1,"2":2}');
var_dump($a);
var_dump(isset($a[1]));
var_dump(isset($a["1"]));
var_dump($a[1]);
var_dump($a["1"]);

Output:

array (size=2)
    '1' => int 1
    '2' => int 2

boolean false

boolean false

ERROR: E_NOTICE: Undefined offset: 1

null

ERROR: E_NOTICE: Undefined offset: 1

null

How do I access these values?

Demo: http://codepad.viper-7.com/8O03IM

解决方案

So, I haven't seen any other answers touch upon this, but @xdazz came close.

Let's start our environment, $obj equals the object notation of a decoded string:

php > $obj = json_decode('{"1":1,"2":2}');

php > print_r($obj);
stdClass Object
(
    [1] => 1
    [2] => 2
)

php > var_dump( $obj );
object(stdClass)#1 (2) {
  ["1"]=>
  int(1)
  ["2"]=>
  int(2)
}

If you want to access the strings, we know the following will fail:

php > echo $obj->1;

Parse error: parse error, expecting `T_STRING' or `T_VARIABLE' or `'{'' or `'$'' in php shell code on line 1

Accessing the object variables

You can access it like so:

php > echo $obj->{1};
1

Which is the same as saying:

php > echo $obj->{'1'};
1

Accessing the array variables

The issue with arrays is that the following return blank, which is the issue with typecasting.

php > echo $obj[1];
php >

If you typecast it back, the object is once again accessible:

php > $obj = (object) $obj;
php > echo $obj->{1};
1

Here is a function which will automate the above for you:

function array_key($array, $key){
    $obj = (object) $array;
    return $obj->{$key};
}

Example usage:

php > $obj = (array) $obj;
php > echo array_key($obj, 1);
1

php > echo array_key($obj, 2);
2

这篇关于不能使用数字键作为字符串的 PHP 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 18:10