dsfgds4215 2010-08-20 02:56
浏览 85
已采纳

PHP:强制转换为(数组)和返回类型:数组不一样?

I have following problem in PHP:

print_r() says it's the same, gettype() says same type, but the last output works not for both cases although they should be the same!

This looks very strange to me.

code and output:

$docdatau = get_object_vars(json_decode($docdata));
$docdatau2 = (array)json_decode($docdata);

echo "1
";
echo gettype($docdatau);
echo "
";
echo "--------------------------------------
";
print_r($docdatau);
echo "--------------------------------------
";

echo "2
";
echo gettype($docdatau2);
echo "
";
echo "--------------------------------------
";
print_r($docdatau2);

echo "out1
";
echo "--------------------------------------
";
print_r($docdatau[0]);
echo "out2
";
echo "--------------------------------------
";
print_r($docdatau2[0]);

The output:

1
array
--------------------------------------
Array
(

    [0] => stdClass Object
        (
            [produkt] => Produkt 2
            [laufzeit] => 24
            [addtext] => sdsd
            [provision] => 39
        )

    [1] => stdClass Object
        (
            [produkt] => Produkt 1
            [laufzeit] => 
            [addtext] => 
            [provision] => 0
        )

)
--------------------------------------
2
array
--------------------------------------

Array
(

    [0] => stdClass Object
        (
            [produkt] => Produkt 2
            [laufzeit] => 24
            [addtext] => sdsd
            [provision] => 39
        )

    [1] => stdClass Object
        (
            [produkt] => Produkt 1
            [laufzeit] => 
            [addtext] => 
            [provision] => 0
        )

)
out1
--------------------------------------
stdClass Object
(
    [produkt] => Produkt 2
    [laufzeit] => 24
    [addtext] => sdsd
    [provision] => 39
)
out2
--------------------------------------
--------------------------------------

out1 and out2 should produce the same results but don't.

Perhaps anybody has a hint for me?

  • 写回答

1条回答 默认 最新

  • dongzhui9936 2010-08-20 07:31
    关注

    There are several PHP bugs about it:

    The same things happens here:

    $obj->{0} = "hello";
    $arr = (array)$obj;
    echo $arr[0];
    

    It happens because the "0" is used as string array key, whereas $arr[0] searches for the integer array key. It is documented in the PHP documentation simply by stating: integer properties are unaccessible (link).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题