2016-08-19 41 views
0

相乘結果我的新的symfony,我試圖建立一個數組應該是這樣的即:symfony的PHP的從查詢

[ '10'=> 100, '100'=> 40,' 200' => 10, '雷斯'=> 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, '雷斯'=> 1]

任何幫助將不勝感激

提前非常感謝!

回答

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}

+0

你是對的,先生!你有任何想法如何我可以使1陣列如果我的結果,而不是一個數組與對象? –

+0

是的,我已經更新了答案 –

+0

嘿,我明白你在做什麼,但由於某種原因,我回來0 1 2 reis而不是10 100 200 reis –