nazanin
nazanin

Reputation: 73

array of floats use in php

In order to draw my chart, I need to have 2 arrays of floats,

  1. The first one stores in MySQL database as a type of string (separated by commas)
  2. And I want to define the second one as a constant array (in PHP)

my problem is how to change the type of data as string(MySQL) and use it as arrays of float in PHP. Also, how should I define the second array? Should I change it to string and then use unserialize?

This just print 1

$data = array();
$data['cols'] = array(
    array('id' => 'Signal','label' => 'Signal', 'type' => 'string'));

$rows = array();
while($r = mysql_fetch_assoc($result)) {
  $temp = array();
  $temp[] = array('v' => $r['Signal']); 
  $res = array_map("floatval", $temp);

  var_dump($res);}                                 

echo var_dump($res);

Upvotes: 1

Views: 2722

Answers (1)

Maxim Kumpan
Maxim Kumpan

Reputation: 2635

You can use a combination of floatval() and array_map() to parse your string array into a float array.

A simple tested example:

$input_array = Array("1.1234", "3.123", "2.23E3", "2.23E-3");

$result = array_map("floatval", $input_array);

var_dump($input_array);
var_dump($result);

Prints:

array(4) {
  [0]=> string(6) "1.1234"
  [1]=> string(5) "3.123"
  [2]=> string(6) "2.23E3"
  [3]=> string(7) "2.23E-3"
}
array(4) {
  [0]=> float(1.1234)
  [1]=> float(3.123)
  [2]=> float(2230)
  [3]=> float(0.00223)
}

P.S.: If your database result is somewhat more structured than just a flat array of float-valued strings, you might need to do more than just map it. Provide some more info on what you have and what you expect for more detailed help.


As for your second array, I'm afraid you can't mark arrays as constant. Here is a relevant question. You can go into classes and autosetters, but I'm not sure that kind of complexity is justified for your requirements.

Upvotes: 1

Related Questions