4

How to display only array value in JSON out in php

I am using below PHP code

echo '{"aaData":'.json_encode($user_details).'}';

And it return below output

{"aaData": [
    {"id":"31","name":"Elankeeran","email":"[email protected]","activated":"0","phone":""}
]}

But I need JSON output like below

{"aaData": [
    {"31","Elankeeran","[email protected]","0","1234"}
]}

Any one please help on this.

3
  • Your example is not valid JSON. {} refers to an object, and objects must have properties like {"id":"31"}. The output returned by your PHP code is valid JSON. Commented Jan 21, 2012 at 14:05
  • Why do you create parts of your JSON manually?! Commented Jan 21, 2012 at 14:08
  • I am using jquery DataTable they asking in this format Commented Jan 21, 2012 at 14:20

3 Answers 3

7
$rows = array();
foreach ($user_details as $row) {
  $rows[] = array_values((array)$row);
}

echo json_encode(array('aaData'=> $rows));

which outputs:

{"aaData": [
    ["31","Elankeeran","[email protected]","0","1234"],
    ["33","Elan","[email protected]","1",""]
]}
Sign up to request clarification or add additional context in comments.

7 Comments

Dor Shemer still I am getting same result
@Elankeeran What's the output of var_dump($user_details) ?
var_dump out here array(3) { [0]=> object(stdClass)#20 (5) { ["id"]=> string(2) "31" ["name"]=> string(10) "Elankeeran" ["email"]=> string(17) "[email protected]" ["activated"]=> string(1) "0" ["phone"]=> string(0) "" } [1]=> object(stdClass)#21 (5) { ["id"]=> string(2) "33" ["name"]=> string(4) "Elan" ["email"]=> string(21) "[email protected]" ["activated"]=> string(1) "1" ["phone"]=> string(0) "" } [2]=> object(stdClass)#22 (5) { ["id"]=> string(2) "34" ["name"]=> string(6) "Elango" ["email"]=> string(17) "[email protected]" ["activated"]=> string(1) "0" ["phone"]=> string(0) "" } }
In that case, you should probaby do json_encode(array('aaData'=> array_values((array)($user_details[0]))))
thanks now i am getting one row like below {"aaData":["31","Elankeeran","[email protected]","0",""]} how to get all rows
|
1
echo '{"aaData":'.json_encode(array_values($user_details)).'}';

should do it

Comments

1

Your PHP is already producing valid JSON. To access items in it from JavaScript, use patterns like:

obj.aaData[0].name;
// Elankeeran

obj.aaData[0].email;
// [email protected]

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.