1

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 Answers 4

3

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);
Sign up to request clarification or add additional context in comments.

Comments

1

In Javascript with JQuery:

jQuery.makeArray();

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

Comments

0

In php, casting:

$aArray = (array) $oObject;

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.