PHP adding key to array from database query

136 Views Asked by At

Wondering if you can help me. I am querying a table to populate a graph with a H axis of time and V axis of count and im trying to dynamically add filters to the graph based on servers in the database table. At this moment its static.

I am using filters to select

i use the following code to query database and add the series to the graph

$results = array();

    foreach( \IPS\Db::i()->select( '*', 'stats', $where, 'time ASC' ) as $row )
    {
        $value = '_'.$row['server'];
        if( !isset( $results[ $row['time'] ] ) )
        {
            $results[ $row['time'] ] = array(
                'time' => $row['time'],
                '_64' => 0,
                '_66' => 0
            );
        }
            //$results[ $row['time'] ][$value] = 0;
            if ($value == '_64')
            {
                $results[ $row['time'] ]['_64'] = $row['value_1'];
            }
            elseif($value == '_66')
            {
                $results[ $row['time'] ][ '_66' ] = $row['value_1'];
            }

        }
        return $results;

and add the filters

$chart->addSeries('_66', 'number');
$chart->addSeries('_64', 'number');

I have tried to make it dynamic by doing

foreach(\IPS\Db::i()->query( "SELECT DISTINCT server FROM stats ORDER BY server" ) as $row)
    {
        $value = '_'.$row['server'];
        $chart->addSeries($value, 'number');
    }

and

$value = '_'.$row['server'];
        if( !isset( $results[ $row['time'] ] ) )
        {
            $results[ $row['time'] ] = array(
                'time' => $row['time'],
                $value => 0,
            );
        }
            $results[ $row['time'] ][$value] = $row['value_1'];

But this did not work in any way. I think im going about adding to the array completely wrong. Any suggestions please?

array should look like this

array (size=8)
 1504025011 => 
array (size=3)
  'time' => int 1504025011
  '_64' => int 2
  '_66' => int 0
 1504094803 => 
array (size=3)
  'time' => int 1504094803
  '_64' => int 0
  '_66' => int 14

but instead

array (size=8)
 1504025011 => 
array (size=2)
  'time' => int 1504025011
  '_64' => int 2
 1504094803 => 
array (size=2)
  'time' => int 1504094803
  '_66' => int 14
1

There are 1 best solutions below

0
On

I managed to make it work in the end. Was a simple in the end. (Normally the case) Sure i tried this before and didn't work. Must have missed something.

I used this code to add keys/value to the array.

foreach(\IPS\Db::i()->query( "SELECT DISTINCT(server) AS Server FROM stats ORDER BY Server DESC;" ) as $rows)
        {
            $value = '_' .$rows['Server'];
            $results[ $row['time'] ][$value] = 0;
        }