【问题标题】:How to convert string as stdClass object to array [PHP]如何将字符串作为 stdClass 对象转换为数组 [PHP]
【发布时间】:2017-02-08 13:08:55
【问题描述】:

我正在使用 API 编写登录系统。 我坚持使用 API 得到的结果。 我得到的结果是这样的普通字符串:

stdClass Object
(
    [success] => 1
    [message] => Array
        (
            [code] => 000
            [txt] => Operation successful
        )

    [data] => Array
        (
            [result] => OK
            [accountID] => 000000000
            [group] => demoCAC
            [currency] => USD
            [enable] => 1
            [read_only] => 0
            [name] => Bogus Demo
            [country] => ****
            [city] => 
            [address] => 
            [phone] => **
            [email] => ***@gmail.com
            [status] => test
            [regdate] => 07/02/2017 09:57
            [lastdate] => 07/02/2017 09:57
            [balance] => 0.00
            [credit] => 0.00
            [equity] => 10000.00
            [isDemo] => 1
            [tp_version] => **
            [last_name] => Demo
            [first_name] => Bogus
            [domain] => ***.com
            [compliance] => 
            [latestTrades] => Array
                (
                    [results] => Array
                        (
                        )

                    [totalResults] => 0
                )

            [owner] => 
        )
    )

那么如何将其转换为数组或可用变量? * 此信息由 (echo) 打印, 我无法访问 $result -> data ->... 是否有一个函数可以将此字符串转换为数组或 json 或可读的东西,以便我可以达到特定值? 当我尝试: print_r(get_object_vars($result)); 我收到此错误:

警告:get_object_vars() 期望参数 1 是对象,字符串在 /home/**/public_html/crm/profile.php 第 20 行给出

【问题讨论】:

  • 您是如何打印这些信息的?如果您使用的是var_dumpprint_r,那么您的结果实际上不是字符串,而是已经是一个对象,因此可以访问其属性(例如,$result->success 将等于成功值,1 in本例)
  • 它似乎是一个var_dump显示..你可以检查eval函数php.net/manual/fr/function.eval.php将字符串转换为php代码
  • 这是你的api返回的字符串吗?如果是,你应该切换到像json这样易于解析的格式。
  • 为我们提供更多代码
  • 也不要使用 EVAL! Fky 的建议非常危险,只会带来伤害。

标签: php arrays object


【解决方案1】:

除非我遗漏了什么,否则你的问题很简单。

查看 var_dump 的内容,您应该能够访问问题中的索引,例如:

$result->data['email'];  // where 'email' is the key of the data.

$result->data['latestTrades']['results']; // nested example.

标准类的所有属性都是公开的,因此可以直接访问。在您的示例中,它们都包含一个数组或嵌套数组,因此可以通过它们的键访问。

【讨论】:

    猜你喜欢
    • 2011-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-29
    • 1970-01-01
    • 2021-11-10
    • 2014-03-01
    • 1970-01-01
    相关资源
    最近更新 更多