0

I know there must an easy and efficient way to do this.

I have an array like this:

       $fields = array( "EVENT_ID" => "Event Id" ,
            "EVENT_NAME"           => "Name",
            "EVENT_CLASSIFICATION" => "Classification",
            "DESCRIPTION"          => "Description",
            "START_TIME"           => "Start Time",
            "END_TIME"             => "End Time"
           );

I would like to convert this as this query:

              Select 
                   "EVENT_ID" as "Event ID",
                   "EVENT_NAME" as "Name", 
                   ...
              from
                   ...

Don't want to put this in Loop. PHP has a lot array handling functions and this must be easy. I am new to php.

Any ideas?

Kevin Rave
  • 13,876
  • 35
  • 109
  • 173

4 Answers4

5

I heavily suggest loops!

$sel = array();
foreach($fields as $key => $val) {
  $sel[] = '`'.$key.'` AS `'.$val.'`';
}
$sel = implode(',', $sel);
dan-lee
  • 14,365
  • 5
  • 52
  • 77
3

A loop is (probably) the way to go here, but you can do it without one. Using array_map.

$sql = implode(',', array_map(function($v, $k){
    return "`$k` AS `$v`";
}, $fields, array_keys($fields)));

NOTE you can only pass functions like this in PHP 5.3+. If you're using 5.2, you can use create_function.

$sql = implode(',', array_map(create_function('$v, $k', 'return "`$k` AS `$v`";'), $fields, array_keys($fields)));
gen_Eric
  • 223,194
  • 41
  • 299
  • 337
  • Thanks! It looks good. Which one is efficient and fast? Loop or this one? – Kevin Rave Apr 17 '12 at 17:24
  • 2
    @KevinRave functions like `array_map()` use loops under the bonnet anyway, there won't be much in it. That said, a C++ loop is likely more efficient than a PHP one, so this is probably slightly better. But so little difference that it's not even noticeable unless you have hundreds of thousands of items. Although this does have the added overhead of calling a function on every iteration of the loop underneath, so YMMV. – DaveRandom Apr 17 '12 at 17:26
2

If you're on 5.3, you can use array_reduce with closures (plain old functions work too, but foreach would be shorter then):

$sql = array_reduce(array_keys($fields), function(&$result, $key) use ($fields) {
  if (!is_null($result)) $result .= ",\n";
  return "{$result}'{$key}' AS '{$fields[$key]}'";
});

Try online

galymzhan
  • 5,505
  • 2
  • 29
  • 45
0

You can simply build your query's string by looping through your values.

$query = '';
foreach($fields as $k => $v)
    $query .= '"' . $k . '" as "' . $v . '",';
echo $query;

Note that this will leave a trailing comma. If you want to remove it, you can use

$query = rtrim($query, ',');

Live example

Alex Turpin
  • 46,743
  • 23
  • 113
  • 145