I’m new to PHP so this might be a very long questions. First of all I can’t normalise the database the way it has been designed it has to be kept like this. I’ll explain the scenario first: I have locations on a map, those locations can have as many products attached to them as possible. My issue is that I want to concatenate two values together in an array to make them into a string so I can store it in the db and then use it.
I’m having issues with a particular record, this record 1234 is causing me issues. As it has two Ratings attached to it but I need to concatenate them and put them into another array so I can store in my database in a particular field as strings instead of separate ints.
Below is the code, as you’ll see I did a if statement inside the code I want to use to debug what is happening in that particular record.
$ratingString = array();
$rating = 0;
foreach( //not sure if this foreach is related to the question)
if(true == isset($ratingString[$location[‘id’]])){
echo ‘in set’;
$ratingString[$location[‘id’]][‘ratingString’] = strval( $ratingString[$location[‘id’]][‘ratingString’]).’,’.$rating;
}else {
if($location[‘id’] == 1234){
echo ‘not in set’
$ratingString[$location[‘id’]][‘ratingString’] = $rating;
Print_r($ratingString);
} }
When I debug this, it shows me two variables in rating string.
Not in set
string() “ratingString”
array(1){
[1234] =>
array(1) {
[“ratingString”] =>
int(2)
}
}
Not in set
string() “ratingString”
array(1){
[1234] =>
array(1) {
[“ratingString”] =>
int(3)
}
}
So what I need help with, is how could I concatenate the two so that it would be [ratingString] => string 2,3 and how would I change my code so that it would work for all my locations and not just this particular record.
My Answer:
To concatenate the two ratings together in the array, you can modify your code as follows:
php
$ratingString = array();
foreach ($locations as $location) {
$rating = 0; // Set the initial rating value
// Check if the location id is set in the ratingString array
if (isset($ratingString[$location['id']])) {
$ratingString[$location['id']]['ratingString'] .= ',' . $rating;
} else {
$ratingString[$location['id']]['ratingString'] = $rating;
}
}
// Print the final ratingString array
print_r($ratingString);
This code will iterate through all locations and concatenate the ratings for each location in the `ratingString` array. The `.` operator is used to concatenate the ratings as strings. This code should work for all locations and not just the specific record 1234.
Rate this post
5 of 5 based on 3606 votesComments