1

I'm trying to fetch data and transform this in json to use with High chart.

Here's my code:

$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;
        }
    $json = json_encode($arr1);
    $json = preg_replace('/"([^"]+)"\s*:\s*/', '$1:', $json);
    debug($json);

And my atual json:

'[{name:"Sotreq",data:"[11]"},{name:"Somov",data:"[1]"},{name:"Soimpex",data:"[0]"}]'

I've used preg_replaceto remove double quotes of keys. I want to remove double quotes for the data value too. Pls help?

Igor Martins
  • 2,015
  • 7
  • 36
  • 57
  • Why would you want to do that? `{data:[11]}`is not the same as `data: "[11]"` – Rangad Feb 09 '14 at 12:54
  • I'm trying to use with highchart PIE type: http://www.highcharts.com/demo/pie-basic . For some reason, with the quotes this don't work. – Igor Martins Feb 09 '14 at 12:56
  • [Ben Hitchcock](http://stackoverflow.com/users/1544013/ben-hitchcock) answer should be correct for the data quetion. Using unquoted object keys seems to be against the spec: [a](http://stackoverflow.com/a/949476/2912456). – Rangad Feb 09 '14 at 13:12

1 Answers1

2

Replace your data line with this one:

   $tmp['data'] =  array(count($value['Branch']));

What are you doing with the json on the other end? Normally you don't need to do any regular expression munging at all, this is the way of madness.

Double quotes in the key field is fine, and optional. It should work with or without the quotes.

Ben Hitchcock
  • 1,368
  • 10
  • 12