0

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!

1 Answer 1

3

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}

Sign up to request clarification or add additional context in comments.

4 Comments

You are right sir! Do you have any idea how I can make 1 array if my result instead of an array with objects?
Hey I understand what you're doing but for some reason I get back 0 1 2 reis instead of 10 100 200 reis
That is strange, I've placed full code, everything is fine on my server
Im very sorry I am just a bit stupid and did something wrong! My apologies

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.