1

I'm trying to print the values from an array as a string. I got this code from the PHP documents, but I'm getting a string conversion error. The values are numbers and I can see them

$viz_array_qry = "SELECT (`column_name`) FROM table_name WHERE option_name='$option_name'";
$result = mysql_query($viz_array_qry);
$result_array = array();
while($row = mysql_fetch_assoc($result))
{
    $result_array[] = $row;
    $viz_array = implode (',',$result_array);
}
    print_r($viz_array);

    //echo $viz_array;  <!-- no result-->

If I var_dump the $result_array I get the list of the values below. But I just want to display them as

0,0,57,39,40

I cant work out why the implode it not working?

 array (size=5)
 0 => 
   array (size=1)
     'column_name' => string '0' (length=1)
 1 => 
   array (size=1)
     'column_name' => string '0' (length=1)
 2 => 
   array (size=1)
     'column_name' => string '57' (length=2)
 3 => 
   array (size=1)
     'column_name' => string '39' (length=2)
 4 => 
   array (size=1)
     'column_name' => string '40' (length=2)

3 Answers 3

3

You should only store value of column_name ($row['column_name']) instead of $row (which is an array) and move implode outside of loop

while($row = mysql_fetch_assoc($result))
{
    $result_array[] = $row['column_name'];
}

echo implode(',', $result_array);
Sign up to request clarification or add additional context in comments.

Comments

0

Implode after the While loop:

$viz_array_qry = "SELECT (`column_name`) FROM table_name WHERE option_name='$option_name'";
$result = mysql_query($viz_array_qry);
$result_array = array();

while($row = mysql_fetch_assoc($result))
{
 $result_array[] = $row;
}

$viz_array = implode (',',$result_array);
print_r($viz_array);

Comments

0

Even if you do not want to change the existing code and store the data in the array as you are doing you can use array_map() to get the result as you want as below

$arr = array(0=>array('column_name'=>'0'),1=>array('column_name'=>'0'),
3=>array('column_name'=>'57'),4=>array('column_name'=>'39'));

function get_col($col) {
    return $col["column_name"];
}

$values = implode(array_map("get_col", $arr), ',');

echo $values ;

3 Comments

Isn't that a workaround on a wrong implementation on his side? I think that adding 2 lines (an array that holds the IDs and the final implode the array) is easier and more understandable than your solution.
Yes thats the reason I mentioned "Even if you do not want to change the existing code" if at all the array needs to be used for some other purpose.
Ok, well I don't need that this time, but thanks for the info Abhik Chakraborty.

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.