我有这种关系Company
hasMany Branch
使用$this->Company->find('all')
输出:
(int) 1 => array(
'Company' => array(
'id' => '4',
'nome' => 'Somov',
'diretores' => 'Marcelo, Carl'
),
'Branch' => array(
(int) 0 => array(
'id' => '3',
'nome' => 'Serra',
'rua' => 'Rua teste 2 exttttt',
'numero' => '22',
'estado' => 'ES',
'cidade' => 'Etc',
'cep' => '',
'responsavel' => '',
'company_id' => '4',
'cnpj' => ''
)
)
),
(int) 2 => array(
'Company' => array(
'id' => '5',
'nome' => 'Soimpex',
'diretores' => ''
),
'Branch' => array()
)
)
我想在像这样的json中将其转换为与Highchart一起使用:
[{
name: NAME OF COMPANY (nome),
data: NUMBER OF BRANCHS
}, {
name: NAME OF COMPANY (nome),
data: NUMBER OF BRANCHS
}]
我如何进行此转换?感谢
答案 0 :(得分:1)
这将返回一个只有一个结果的json对象。
如果我们使用前面的例子,可以这样做:
$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);
答案 1 :(得分: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);
?>
这将生成一个名为results.json的文件,其中您的php文件存储在您的在线服务器上,从您的MySQL数据库中获取url和title变量,您可以将变量名称更改为您想要获取的内容。
答案 2 :(得分:0)
整个想法就像这样
$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);