i can separate join column with comma, but how to remove comma if on the second column is null? in below, i have 2 column i want join otot2 and otot3 1. how to not shown comma after otot2 if otot3 null? 2. and how to not shown anything comma if otot2 and otot 3 null? 3. otot2 and otot3 flexible ( not always has data)
here my php code for output query:
if(mysqli_num_rows($hasil) > 0)
{
$response = array();
while($data = mysqli_fetch_array($hasil))
{
$h['main muscle'] = $data['otot1'];
$h['other muscle'] = $data['otot2'].', '.$data['otot3'];
array_push($response, $h);
}
$response["success"];
echo json_encode($response);
A simple solution would be -
$response = array();
while($data = mysqli_fetch_array($hasil))
{
// other code
$temp = array($data['otot2'], $data['otot3']); // Store them in array
$temp = array_filter($temp); // remove empty values
$h['other muscle'] = implode(',', $temp); // implode them with (,)
// Other codes
array_push($response, $h);
}
By using array_filter
& implode
you don't have to worry about the ,
, as array_filter
would remove the empty values and if there is 2 values in the array them the string would be ,
separated else not.
Or you can try this also
$h['other muscle'] = $data['otot2'];
if($data['otot3'] !== null)
$h['other muscle'] .= ', ' . $data['otot3']; // Concatenate