Frank Lucas - 2 months ago 6x

PHP Question

I am new to symfony and I am trying to build an array that should look like this:

['10' => 100, '100' => 40, '200' => 10, 'reis' => 1]

The data comes from my database obviously, so here is my query:

`$chances = $conn->fetchAll("SELECT * FROM prices");`

This results an array with objects:

`[{"id":"1","price":"10","amount":"1000","chance":"0,5"},`

{"id":"2","price":"100","amount":"100","chance":"0,2"},

{"id":"3","price":"200","amount":"10","chance":"0,05"},

{"id":"4","price":"reis","amount":"1","chance":"0,005"},

{"id":"5","price":"noprice","amount":"0","chance":"0,245"}]

Now I need to multiply the chance by 200 and fill my array I do this like so:

`foreach ($chances as $chance){`

$p = $chance['price'];

$c = (200 * $chance['chance']);

$chancesArr[] = array($p => $c);

}

But for some reason I get always 0 as a result

Anyone knows why the multiply doesnt work?

And I have another little problem the $chancesArr is a multidimensional array but it should be 1 array with keys as the $p and values are the $c

My result:

[{"10":0},{"100":0},{"200":0},{"reis":0}]

My goal:

['10' => 100, '100' => 40, '200' => 10, 'reis' => 1]

Any help would be greatly appreciated

Many thanks in advance!

Answer

I think that it is because of comma in number, try to replace comma by point

```
$chances = '[{"id":"1","price":"10","amount":"1000","chance":"0,5"},
{"id":"2","price":"100","amount":"100","chance":"0,2"},
{"id":"3","price":"200","amount":"10","chance":"0,05"},
{"id":"4","price":"reis","amount":"1","chance":"0,005"},
{"id":"5","price":"noprice","amount":"0","chance":"0,245"}]';
$chances = json_decode($chances, true);
foreach ($chances as $chance){
$p = $chance['price'];
$c = 200 * str_replace(',', '.', $chance['chance']);
$chancesArr[$p] = $c;
}
echo json_encode($chancesArr);
```

output: `{"10":100,"100":40,"200":10,"reis":1,"noprice":49}`

Source (Stackoverflow)

Comments