b0w3rb0w3r
b0w3rb0w3r

Reputation: 937

Adding dynamic variables to an array

    foreach ( $tbl_one_data as $row_ ) {
        $id = ( int ) $row_ [0];
        $time = mysql_real_escape_string ( $row_ [1] );
        $callid = mysql_real_escape_string ( $row_ [2] );
        $queuename = mysql_real_escape_string ( $row_ [3] );

        $arrayValues [] = "($id, '$time','$callid','$queuename',";
    }
}

I am trying to improve the above code with the code below:

$b = 0;
        foreach ( $tbl_one_data as $row_ ) {
            if ($b < count ( $row_ )) {
                ${"var" . $b} = mysql_escape_string ( $row_ [$b] );
                $b ++;
            }
        }

My question is how would I add the dynamic variables created into the array incrementally to achieve something like this: $arrayValues [] = "('$var0','$var1','$var2','$var3'"; ??

$arrayValues [] = "('${"var" . $b}',"; doesn't seem to have the same effect as in my first code snippet.

Upvotes: 0

Views: 63

Answers (2)

fbas
fbas

Reputation: 1674

I believe this is what you're asking for:

foreach ( $tbl_one_data as $row_ ) {
    $arrayValues [] = "('" . implode("','", $row_) . ",";
}

All the elements in $row_ are concatenated together into a string by implode() using a comma and single quotes as the "glue".

If this doesn't help or isn't what you wanted, leave a comment and we'll try to get better feedback.

Upvotes: 1

FatalError
FatalError

Reputation: 550

You can make it simply by using below code:

foreach ( $tbl_one_data as $row_ ) {
    $newArr = array();
    $newArr[] = ( int ) $row_ [0];
    $newArr[] = mysql_real_escape_string ( $row_ [1] );
    $newArr[] = mysql_real_escape_string ( $row_ [2] );
    $newArr[] = mysql_real_escape_string ( $row_ [3] );

    $arrayValues [] = $newArr;
}

Upvotes: 0

Related Questions