简体   繁体   English

为什么数组索引未定义未定义?

[英]Why is the array index is undefined undefined?

I'm having trouble finding out why is the following code not working.我无法找出为什么以下代码不起作用。

I've a JSON answer from a remote server, containting the following data:我有一个来自远程服务器的 JSON 答案,其中包含以下数据:

...., "UserId":{"50423":"Free Kkludkjta","54379":"Sjkllyu\u00e9lkj Nolla","67103":"Tswt\u00f3 BLLA","64469":"Uz\u00e1h G","46699":"RT\u00e1sdt UTSF","46873":"Tam\u00e1s XXXX"}, ...

(names are swapped, but since there are some special chars in the aswer I've kept those) (名称已交换,但由于答案中有一些特殊字符,我保留了这些字符)

And I have the following code sniplet, which gives 'array index undefined for idx 64469':我有以下代码片段,它给出了“未定义 idx 64469 的数组索引”:

$proj_schema = json_decode($proj_schema);
                        var_dump($proj_schema->UserId);
                        $avail_users = (array)$proj_schema->UserId;
                        var_dump($avail_users);
                        var_dump($avail_users[64469]);

The output is the following:输出如下:

C:\wamp\www\j34\administrator\components\com_mycomponent\views\myview\view.html.php:113:
object(stdClass)[309]
  public '50423' => string 'Name1' (length=14)
  public '54379' => string 'Name2' (length=18)
  public '67103' => string 'Name3' (length=12)
  public '64469' => string 'Name4' (length=15)
  public '46699' => string 'Name5' (length=11)
  public '46873' => string 'Name6' (length=12)

C:\wamp\www\j34\administrator\components\com_mycomponent\views\myview\view.html.php:115:
array (size=6)
  '50423' => string 'Name1' (length=14)
  '54379' => string 'Name2' (length=18)
  '67103' => string 'Name3' (length=12)
  '64469' => string 'Name4' (length=15)
  '46699' => string 'Name5' (length=11)
  '46873' => string 'Name6' (length=12)

Notice: Undefined offset: 64469 in C:\wamp\www\j34\administrator\components\com_mycomponent\views\myview\view.html.php on line 116

If I walk through the array with foreach and write out the element based on 'if ($key == 64469)' it echos the name, but I cannot access the name by array key.如果我使用 foreach 遍历数组并根据“if ($key == 64469)”写出元素,它会回显名称,但我无法通过数组键访问名称。

Results are same with PHP 5.6.32 (I know) and PHP 7.1.0.结果与 PHP 5.6.32(我知道)和 PHP 7.1.0 相同。 Result is the same if I put the id in "" or '';如果我把 id 放在 "" 或 '' 中,结果是一样的;

What am I missing with the casting?我在选角上缺少什么?

You are using the JSON as an object and not as an array.您将 JSON 用作对象而不是数组。 Therefore, the key does not exist, because it is a property.因此,密钥不存在,因为它是一个属性。

Decode with true as 2nd argument to get an array instead of an object.使用true作为第二个参数进行解码以获取数组而不是对象。

$proj_schema = json_decode($proj_schema, true);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM