Yanuar Ihsan Yanuar Ihsan - 1 year ago 54
PHP Question

PHP rewrite array to string,

in this case, for example,
i have string from array of person_code => 1,2,3
then i want change that string to another string from array of person_nama => name1, name2, name3

i have try with my code :

public function Person_name($person_code)
$code= explode(',', $person_code);
for($i=0; $i<count($code); $i++){
$sql= Yii::app()->db->createCommand('select nm_person from tbl_person where kd_person="'.$code[$i].'";');
$namearray= implode(',',$name);
return $namaarray;

but that result is only return the last person name in array,

anyone can help me?? thank you

Answer Source

I'd just answer this by just using a band-aid solution with just normally pushing the results into the array. Your current code is just overwriting $name.

$name[] = $sql->queryRow();


Don't directly interpolate variables into the query string. Just stop that, you're already using a good framework with useful query builder.

Instead of executing each query for each id, why not use a WHERE IN clause flavor along with the builder.

Much better untested basic idea:

public function Person_name($person_code)
    $persons = array();
    $person_code = explode(',', $person_code);

    if(!empty($person_code)) {
        $result = Yii::app()->db->createCommand()
        ->setFetchMode(PDO::FETCH_COLUMN, 0)
        ->where(array('IN', 'kd_person', $person_code)

        $persons = implode(', ', $result);

    return $persons;

Based on reading the manual