开发者

Access array by string key x, where x is "123"

We have an array of which the keys are Strings, but those strings sometimes just are numbers (e.g. "123"). When trying to access开发者_运维知识库 the array by the key "123", we get an Undefined Index notice. When accessing it by just the integer 123, we get the Undefined Offset notice. This tells us we're trying to index it correctly using the "123" string, but it's still not set.

Trying to come up with an example for this SO question this is hard, since PHP converts array keys in our test case to integers automatically, while in our real-world application this does not happen (due to use of a Java Bridge). The test array we're trying now is:

<?php
$array = array("123" => array(108, 8));
var_dump($array);
?>

This returns:

array(1) { [123]=> array(2) { [0]=> int(108) [1]=> int(8) } }

While in our real-world equivalent, it would return:

array(1) { ["123"]=> array(2) { [0]=> int(108) [1]=> int(8) } }

So in the real world the index actually is a String:

<?php
var_dump(array_keys($array));
?>

returns

array(1) { [0]=> string(3) "123" }

So, finally the question is the output of the following code:

<?php
foreach ($array as $key => $value) {
    if (!isset($array[$key])) {
        print "What is happening here?";
    }
} 
?>

which gives:

What is happening here?

Based on Yoshi's comment, here's working test code:

<?php
$array = (array)json_decode('{"123":[108,8]}');
foreach ($array as $key => $value) {
    if (!isset($array[$key])) {
        print "What is happening here?";
    } else {
        print "Nothing to see here, move along";
    }
} 
?>


Not very elegant solution too, but also works and do not require recreating array. Also, you can access the element value.

$array = (array)json_decode('{"123":100}');
$array_keys = array_keys($array);
$array = (object)$array;

foreach ($array_keys as $key)
{

    if (!isset($array->$key))
    {
        print "What is happening here?";
    }
    else {
        print "It's OK val is {$array->$key}";
    }
} 

Note $ before key in $array->$key, it is important.


Look at this code (and line $array[(string)$key])

<?php
$array = array("123" => array(108, 8));

foreach ($array as $key => $value)
{
    if (!isset($array[(string)$key]))
    {
        print "What is happening here?";
    }
    else print "It's just types";
} 

Type of $key was automatically casted to integer, and it's why this key was not found in array.

All information about it you can find in manual: http://php.net/manual/en/language.types.type-juggling.php

This code will works with both cases:

foreach ($array as $key => $value)
{
    if (!array_key_exists($key, $array))
    {
        print "What is happening here?";
    }
    else print "It's just types";
} 


I had the same problem (but with array_intersect_key).

Here is my solution:

$array = array_combine(array_keys($array), $array)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜