score:1

Accepted answer

This will return a json object with only one result.

If we use previous example, can be done like this:

$arr = $this->Company->find('all'); // fetch the array
$arr1 = array();
foreach ($arr as $value) {
    $tmp = array();

    $tmp['name'] = $value['Company']['nome'];
    $tmp['data'] = count($value['Branch']);

    $arr1[] = $tmp;
}
return json_encode($arr1);

score:0

The whole idea is about like this

$arr=$this->Company->find('all'); // fetch the array
$arr1=array();
foreach ($arr as $value) {
    $arr1['name']=$value['Company']['nome'];
    //some more manual transform to desire format
}
return json_encode($arr1);

score:1

<?php 
 $sql=mysql_query("select * from Posts limit 20"); 

 $response = array();
 $posts = array();
  while($row=mysql_fetch_array($sql)) 
  { 
    $title=$row['title']; 
    $url=$row['url']; 

    $posts[] = array('title'=> $title, 'url'=> $url);

  } 

    $response['posts'] = $posts;

    $fp = fopen('results.json', 'w');
    fwrite($fp, json_encode($response));
    fclose($fp);


  ?> 

This will generate a file called results.json file where your php file is stored on your online server, taking url and title variables from your MySQL db, you can change the variable names to what you want to fetch.


Related Articles