So, I have 2 arrays that I've combined into one array after making sure they're the same length as such.
//Fetching Ratings for All Coaches & Making a Key, Value Associative Array with Coach id as Key and Rating as Value
$coaches = $coachRepository->findAll();
$rating = $coachRepository->findRatingByCoach();
//Array of coach IDs
$id_array = array();
foreach ($coaches as $c){
$id_array[] = $c->getId();
}
$combined = array_combine($id_array, $rating);
Now I want to pass this key, value array to Twig template and JavaScript. I'm currently doing this
return $this->render('...', [
..., 'combined'=>$combined
]);
And I'm accessing the array in Twig as such
{% for key, value in combined %}
{{ key }} - {{ value }}
{% endfor %}
And I'm getting this error.
Object of class App\Entity\Coach could not be converted to string
Looking at the Stack Trace I can see that the array combined is being passed in this form.
'combined' => array(object(Coach))
After a bit of debugging it turns out that I thought the issue was with the $id_array
when in fact it's the $rating
variable that's presenting an issue. I'm not sure why but I'm getting a single float value.
I fixed the issue by changing how I'm fetching the $rating, now instead of using a QueryBuilder to get it from the DB, I'm getting it from list of Coaches as such
//Array of coach IDs and array of Ratings
$id_array = array();
$rating_array = array();
foreach ($coaches as $c){
$id_array[] = $c->getId();
$rating_array [] = $c->getRating();
}
Even if I set the array
CodePudding user response:
After a bit of debugging it turns out that I thought the issue was with the $id_array when in fact it's the $rating variable that's presenting an issue. I'm not sure why but I'm getting a single float value. I fixed the issue by changing how I'm fetching the $rating, now instead of using a QueryBuilder to get it from the DB, I'm getting it from list of Coaches as such
//Fetching Ratings for All Coaches & Making a Key, Value Associative Array with Coach as Key and Rating as Value
$coaches = $coachRepository->findAll();
//Array of coach IDs and array of Ratings
$id_array = array();
$rating_array = array();
foreach ($coaches as $c){
$id_array[] = $c->getId();
$rating_array []= $c->getRating();
}
$this->debug_to_console($id_array[0]);
$combined = array_combine($id_array, $rating_array);
I'm still accessing the array in the same way in twig