PHP数组用数字键作为字符串不能使用 [英] PHP array with numeric keys as string can't be used

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

问题描述

我有一个具有数字键为字符串类型PHP数组。

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

但是,当我试图访问这些PHP是给我一个未定义的索引错误。

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"]);

输出:


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?

演示:的http://$c$cpad.viper-7.com/8O03IM

推荐答案

所以,我还没有看到任何其他的答案触及这一点,但@xdazz差点。

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

让我们开始我们的环境, $ OBJ 等于脱codeD字符串对象表示法:

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

访问对象变量

您可以像这样访问:

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

这是相同的话说:

Which is the same as saying:

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

访问数组变量

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

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};
}

实例:

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

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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆