Question

Some assistance would be greatly appreciated:

The 'foreach' section works perfectly and echo's the result set perfectly; as soon as I try the implode it fails? Thank you!

$ctr = 0;
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {

    $RespondentsResultSetArray[$ctr] = array(
        "Firstname" => $row['cnt_firstname'],
        "Lastname" => $row['cnt_lastname']
    );

    $ctr = $ctr + 1;
}

foreach ($RespondentsResultSetArray as $key) {
    echo $key["Firstname"] . ' ' . $key["Lastname"] . ', ';
}

sqlsrv_free_stmt($stmt);

echo implode(', ',array_values($RespondentsResultSetArray));
Was it helpful?

Solution 2

You are passing an array of arrays to implode function. Here is a little deviation of your code, that should get you to the same result:

$full_array = array();
foreach ($RespondentsResultSetArray as $key) {
    echo $key["Firstname"] . ' ' . $key["Lastname"] . ', ';
    array_push($full_array,$key["Firstname"]);
    array_push($full_array,$key["Lastname"]);

}



echo implode(', ',$full_array);

Also, for the future, try to chose smaller names for your variables, and use lowercase for your variable names and array index.

OTHER TIPS

try this

implode(',',$RespondentsResultSetArray);

The php implode function accepts an array of strings. You are not passing it an array of strings.

To user1844933 that just answered, your suggestion would pass implode an array of arrays. That won't work for the same reason.

$RespondentsResultSetArray=array();
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
    array_push($RespondentsResultSetArray,$row['cnt_firstname'].' '.$row['cnt_lastname']);
}
$saved_to_variable=implode(', '$RespondentsResultSetArray);

Will create an array of strings which you can then implode

Since you recently commented that you want to save it to a variable rather than echo it, I just changed the last line of the example code. I believe that will give you the properly spaced, and delimited string that you desire.

since$RespondentsResultSetArray is multidimensional array use foreach loop before echo

$string = ""; 
foreach($RespondentsResultSetArray as $values)
{
echo implode(array_values($values),",");
$string= $string.",".implode(array_values($values),",");
}

$string=ltrim($string,",");
echo $string;

Demo

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top