RedGiant
RedGiant

Reputation: 4748

How to add {text} (without quotes) to an array in PHP for Google Chart API?

Updated following Uberfuzzy advice:

 $a = '{"role": "tooltip","p": {"html": true}}';
 $aa = json_decode($a,true);
 $data[0] = array_merge(array(product),$info,array($aa));

This thread shows how to customize the html content of the tooltip in Google Chart API using arrayToDataTable. It requires the format like this:

[
        ['Country', 'Value', {role: 'tooltip', p:{html:true}}],
        ['Russia', 5, 'Hello world<br>test'],
        ['US', 20, '<img src="logo6w.png"/>']
]

Fiddle Example.

I was using AJAX to generate a JSON output from mysql and pass into arrayToDataTable function. The code below gives me this output:

[["product","diameter","width"],["Product 1",2,4],["Product 2",4,8]]

$_POST["info"] Content:

Array
(
    [0] => diameter
    [1] => width
)

PHP Code:

$rows = $users->fetchAll();
$data="";
$data[0] = array_merge(array(product),$info);   
$i = 1;
foreach ($rows as $row)
{
    $d[]=$row["name"];
    foreach($_POST["info"] as $p)
    {    
        $d[]= $row[$p];
    }
    $data[$i] = $d;
    $d=array(); //set $d to empty not to get duplicate results
    $i++;
}   
echo json_encode($data,JSON_NUMERIC_CHECK);

How can I insert {role: 'tooltip', p:{html:true}} in $data[0]? It isn't an array, so I can't simply use

$data[0] = array_merge(array(product),$info,array({role: 'tooltip', p:{html:true}}));  

jQuery:

 function drawChart() {
      var info = $('input:checked').map(function(){
       return $(this).val()
      }).get();
      var tt = $('.tt').map(function(){
       return $(this).data('tid')
      }).get(); console.log(tid);

      var title = $('h3').text()
      var jsonData = $.ajax({
            url: "test.php",
            type:"POST",
            dataType: "json",
            data:{'info[]':info,'tt':tt},
            async: false
      }).responseText;

      var data = google.visualization.arrayToDataTable($.parseJSON(jsonData));


      var options = {
       tooltip: {isHtml: true},
       hAxis: { 
        textStyle: {fontSize: 11},
        slantedText: true, 
        slantedTextAngle: 40

       }

      };

      var chart = new google.visualization.LineChart(
                    document.getElementById('chart'));
      chart.draw(data, options);
    }

Upvotes: 0

Views: 324

Answers (2)

asgallant
asgallant

Reputation: 26340

json_encode converts PHP's associative arrays to javascript objects, so to create {role: 'tooltip', p:{html:true}}, you would create a PHP array like this:

$jsObj = array(
    'role' => 'tooltip',
    'p' => array(
        'html' => true
    )
);

Upvotes: 1

Uberfuzzy
Uberfuzzy

Reputation: 8372

It looks like your {role: 'tooltip', p:{html:true}} is json, so run json_decode (remember to pass true as the 2nd param) on it to get a php native array, THEN do your array merging.

Upvotes: 1

Related Questions