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

如何在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?

我有一个返回一些对象的jQuery帖子。 p>

所以,我 有一个数据库查询结果我做 json_encode($ result) code>然后我把它作为响应发送到jQuery帖子里面的 success code>函数。 p>

如果我在console.log中看到响应,我会看到多个对象。 我想要的是将响应作为数组数组发送。 p>

在PHP中 p>

  json_encode($ results)
  代码>  pre> 
 
 

在javascript中: p>

  success:function(json){
 console.log(json); 
} \  n  code>  pre> 
 
 

在控制台日志中: p>

  [> Object,> Object,> Object] 
   pre> 
 
 

有什么想法吗? p> div>

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

In php, casting:

$aArray = (array) $oObject;

In Javascript with JQuery:

jQuery.makeArray();

http://api.jquery.com/jQuery.makeArray/

json encode will encode a string as a json OBJECT which in javascript is an object. in javascript an array is simply an object with special helper functions. there shouldn't be a need to create an array from the object as you can manipulate an object as easily as you can manipulate an array.