如何访问阵列的某些部分以用于flot图表?

问题描述:

I've got an array below via print_r, however I need to only use part of this so I can use it in flot charts.

Array ( [success] => 1 [timestamp] => 1383824357 [data] => Array ( [0] => Array ( [label] => customer1 [SUM(value)] => 12345) [1] => Array ( [label] => customer2 [SUM(value)] => 67890) [2] => Array ( [label] => customer3 [SUM(value)] => 11223 ) [3] => Array ( [label] => customer4 [SUM(value)] => 33445 ) ) )

The format that flot charts want is like so (with the above data used):

[
    { label: "customer1",  data: 12345},
    { label: "customer2",  data: 67890},
    { label: "customer3",  data: 11223},
    { label: "customer4",  data: 34455}
];

Does anyone know how I can go about accessing the data as above?

我通过print_r在下面有一个数组,但是我只需要使用其中的一部分,所以我可以使用它 在flot chart中。 p>

数组([success] => 1 [timestamp] => 1383824357 [data] =>数组([0] = >数组([label] => customer1 [SUM(value)] => 12345)[1] =>数组([label] => customer2 [SUM(value)] => 67890)[2 ] =>数组([label] => customer3 [SUM(value)] => 11223)[3] =>数组([label] => customer4 [SUM(value)] = > 33445))) p> blockquote>

flot图表想要的格式是这样的(使用上面的数据): p>

  [
 {label:“customer1”,data:12345},
 {label:“customer2”,data:67890},
 {label:“customer3”,data:11223},
 {  label:“customer4”,数据:34455} 
]; 
  code>  pre> 
 
 

有谁知道如何访问上述数据? p> \ n div>

so u basically want to change the "data" key with the "SUM(value)" key and then accessing the array? if so u can use this snippet:

<?php
echo json_encode($data);

function array_change_key_name( $orig, $new, &$array ) {
  foreach ( $array as $k => $v ) {
    $res[ $k === $orig ? $new : $k ] = ( (is_array($v)||is_object($v)) ? array_change_key_name( $orig, $new, $v ) : $v );
  }
  return $res;
}

$new = array_change_key_name("data" ,"SUM(value)" , $data);
echo json_encode($new);
?>

EDIT: The code change the key data in the key SUM(value) ... if i understand well u want the opposit ... just invert the function parameters like this

$new = array_change_key_name("SUM(value)" ,"data" , $data);

there is also another way to do the same thing, but u will have to change the query from:

Select SUM(value) etc etc

to

Select SUM(value) as data etc etc

and the DB will handle all for u :)

Just convert convert it to a JSON object:

$json = json_encode($array['data']);

Then you've got the structure you need.

You might need to change the field names from value to data aswell.

print_r($array['data']); // $array is the name of your array

You can do:

foreach ($myArray as $val) {
    echo $val['data'].'<br />';
    // Do whatever you want to do here
}

Try this May be it will Work . I didn't tested ...

 $myArray = "Your array";
 $data = $myArray['data'];
 $js_ar = '"';
    foreach($data as $record)
    {
        $js_ar .= '{ "label": $record[label],  data: $record[SUM(value)]}';

    }
    $js_ar = '"';
    $json_data = json_encode($js_ar);

    print_r ($json_data);