duankua3620 2016-06-02 17:53
浏览 141
已采纳

没有类的对象:添加新字段并返回JSON

My question is a variation of the following post here added to JSON logic. I´m using PHP 5.6.22

I need to build a class without an object at runtim to build a JSON object of same type to be returned to the client. My code:

public static function getData()
{
    $columns = array ("Name", "Address", "Age" );
    $values  = array ("John", "A Ave 222", 32 );

    $ret = (object)[];
    $index = 0;

    foreach ($columns as $col)
    {
        $value = $values[$index++];
        $ret[] = (object) [$col => $value]; // Error here
    }

    return json_encode($ret);
}

When running that I get the following error:

<b>Fatal error</b>:  Cannot use object of type stdClass as array in <source filename> on line <linenumber>

Help appreaciated to solve that...

  • 写回答

2条回答 默认 最新

  • dongningce9075 2016-06-02 18:07
    关注

    In PHP you can add new property to array just by setting it

    $columns = array ("Name", "Address", "Age" );
    $values  = array ("John", "A Ave 222", 32 );
    
    $ret = (object) [];
    $index = 0;
    
    foreach ($columns as $col)
    {
        $value = $values[$index++];
        // You can create and add new property to object in php by such way
        $ret->$col = $value; 
    }
    
    echo json_encode($ret);  // {"Name":"John","Address":"A Ave 222","Age":32}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥30 用arduino开发esp32控制ps2手柄一直报错
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿