dqwcdqs358367 2011-12-02 20:39
浏览 55
已采纳

如何在php中将对象转换为数组数组?

I have a jQuery post that returns some objects.

So, I have a DB query result that I do json_encode($result) and then I send it as a response in the success function inside the jQuery post.

If I console.log the response I see multiple objects. What I want is to send the response as an array of arrays.

In PHP

json_encode($results)

In javascript:

success: function(json) {
  console.log(json);
}

In console log:

[>Object , >Object , >Object]

Any ideas?

  • 写回答

4条回答 默认 最新

  • douping3427 2011-12-02 20:55
    关注

    Your $results in php is an array of objects or of associative arrays. Make it an array of numerically-indexed arrays before you send with casting:

    // ASSUMING each $result object does not have its own nested arrays
    foreach ($results as &$result) {
        $result = array_values((array) $result);
    }
    

    Note you will lose the ability to get items by column name.

    But please step back and think about where your $result comes from.

    If you are using mysql driver, consider doing this when building your result:

    $results = array();
    // Note we use MYSQL_NUM option, so $row looks like array('col1value', 'col2value')
    while (FALSE !== ($row = mysql_result_array($resource, MYSQL_NUM))) {
        $results[] = $row;
    }
    
    json_encode($results);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效