Genadinik
Genadinik

Reputation: 18639

PHP - how do I return JSON in a specific format I need?

I have a PHP file which currently returns JSON in these two ways:

If an error happens, I do this:

$post_data = array('error' => "no_member_id");
echo json_encode($post_data);

and if there is no error, and I need to return data in JSON format, I do this:

if (mysql_num_rows($result) > 0 )
{
         $rows = array();
         while($r = mysql_fetch_assoc($result))
         {
             $rows[] = $r;
         }

         echo json_encode($rows);
}

But what I really need to do is return the data in a format like this:

{"result":"ok", data :[{"data1":"value1", "data2":"value2"}]}

or this:

{"result":"error", data :[{"error":"no_id"}]}

Could someone please help me understand how to do that?

Thanks!!

Upvotes: 0

Views: 91

Answers (3)

Pedro Cordeiro
Pedro Cordeiro

Reputation: 2125

echo json_encode( array( "result" => "ok", "data" => $rows ) );

instead of

echo json_encode($rows);

Upvotes: 2

Vijay Verma
Vijay Verma

Reputation: 3698

Just add result key with specific value in both array:

echo json_encode(array("result" => "ok", "data" : $rows));

and

echo json_encode(array("result" => "error", "data" : $post_data));

Upvotes: 1

djjjuk
djjjuk

Reputation: 358

first, stop using mysql built in functions. they will be deprecated.

try this:

$result = 0;
$json = array(
 'result' => 'ok',
 'data'   => array()  
);
if (mysql_num_rows($result) > 0 )
  while($r = mysql_fetch_assoc($result)) {
    $json['data'][] = $r;
  }
} else {
  $json['result'] = 'error';
  $json['data'] = array('error' => "no_member_id");
}
echo json_encode($json);

Upvotes: 1

Related Questions