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).

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

报告相同问题?

悬赏问题

  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害