symfony php从查询

时间:2016-08-19 10:17:04

标签: php arrays symfony

我是symfony的新手,我正在尝试构建一个看起来像这样的数组:

  

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

数据显然来自我的数据库,所以这是我的查询:

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

这会产生一个包含对象的数组:

[{"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"}]

现在我需要将机会乘以200并填充我的数组,我这样做:

foreach ($chances as $chance){
  $p = $chance['price'];
  $c = (200 * $chance['chance']);
  $chancesArr[] = array($p => $c);
}

但由于某种原因,我总是得到0

任何人都知道为什么乘法不起作用?

我有另一个小问题$ chancesArr是一个多维数组,但它应该是1个数组,键为$ p,值为$ c

我的结果:

  

[{ “10”:0},{ “100”:0},{ “200”:0},{ “现实”:0}]

我的目标:

  

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

非常感谢任何帮助

非常感谢提前!

1 个答案:

答案 0 :(得分:3)

我认为这是因为数字上的逗号,尝试按点替换逗号

$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);

输出:{"10":100,"100":40,"200":10,"reis":1,"noprice":49}