Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP implode array with prefix and commar seperated

Tags:

php

I am trying to build an sql query using an array and add a prefix.

E.g:

$columns = array('column1', 'column2');

"SELECT ". ltrim(implode(", media_", $columns), ', ') . " FROM media WHERE media_id = '{$id}'";

Outputs:

SELECT filename, media_image FROM media WHERE media_id = '3'

What I really want:

SELECT media_column1, media_column2 FROM media WHERE media_id = '3'

Question: How can I: 1. Prefix all items of the array with "media_" 2. Separate more than 1 item with a comma?

like image 496
John Magnolia Avatar asked Dec 15 '22 18:12

John Magnolia


1 Answers

why not put "media_" to the front?:

$columns = array('column1', 'column2');
$selectColumns = 'media_' . implode(', media_', $columns);

"SELECT {$selectColumns} FROM media WHERE media_id = '{$id}'";

you can also use array_map:

$columns = array_map(function($column) {
    return 'media_' . $column;
}, $columns);

"SELECT " . implode(',', $columns) . " FROM media WHERE media_id = '{$id}'";
like image 112
Vitaly Muminov Avatar answered Dec 23 '22 16:12

Vitaly Muminov