This should be easy, but...

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View

I'm trying to build a simple, one-dimensional array of prices, where the key
to each element is the product code.

So I start by executing a select query "SELECT Code, Price FROM Products",
and the results are returned in a two-dimensional array, $data, which I can
loop through like this:

while (list(, $value) = each($data))
    $code = $value[0];
    $price = $value[1];

I would have thought I could build my array here by writing something like:

    $command = "$arr['$code'] = $price;";

But this doesn't work.

Can anyone explain?

Re: This should be easy, but...

while (list(, $value) = each($data))
     $code = $value[0];
     $price = $value[1];
     $command = "$arr['$code'] = $price;";  // I belive you
                                             // need \ before all $s
     exec($command);                         // you want eval() here
     // wouldn't this be a bit more concise:
     $arr[$code] = $price;   // why all the command and eval hubbaabaloo?

or how about this:
foreach ( $data as $values )
   $arr[$values[0]] = $values[1];
   // or if you used  mysql_fetch_assoc or mysql_fetch_array:
   // $arr[$values['Code']] = $values['Price'];

Quoted text here. Click to load it

Re: This should be easy, but...

Captain Nemo wrote:

Quoted text here. Click to load it

there are some errors in your code..
if you want an array like this
'code' => 'price'
you can do something like this..

while(list($code, $value) = mysql_fetch_array($data))
        $product[$code] = $value;


OK - mystery solved!

Panic over!

I was confusing the exec() function with the eval() function.

Site Timeline