SitePoint Sponsor

User Tag List

Results 1 to 8 of 8

Threaded View

  1. #1
    SitePoint Addict
    Join Date
    Jul 2006
    Fionnphort, Isle of Mull, Scotland
    1 Post(s)
    0 Thread(s)

    Turning an array into (part of) a MySQL query string

    I frequently need to turn a PHP array such as:
    PHP Code:
    $cols = array ( [access] => [card] => [child] => [cot] => [dinner] => [ground] => [allyear] => [pets] => [wifi] => )
    // derived from 'print_r', I'm aware this is not how one would construct the array 
    into a string (part of a query string for MySQL):
    PHP Code:
    $cols_new "access = 'N', card = 'N', child = 'Y', cot = 'Y', dinner = 'N', ground = 'Y', allyear = 'Y', pets = 'N', wifi = 'Y'" 
    I've done it with a FOREACH loop, but I'm just curious to know if there's a better way (e.g. an array function I've missed).
    Implode just gives me a string of the values. "N, N, Y, Y, N, Y, Y, N, Y". I've wondered about 'Array_walk' but even if it were to work there will be at least as many lines of code as with the FOREACH loop:
    PHP Code:
        $cols_new '';
        foreach (
    $cols as $key => $value) {
    $cols_new .= $key " = '" $value "', ";
    $cols_new substr($cols_new0, -2);  // remove trailing comma and space 
    I am using this procedure quite freqently, so if there's a better/shorter way it could be handy when I come to anonymise it.
    In short what I'm looking for is:
    PHP Code:
    $cols_new someExistingPHPFunction($cols); 
    Failing which I'll have to write my own based on what I've done so far.
    Last edited by ramasaig; Sep 12, 2011 at 05:07. Reason: clarify origin of the arrays
    Tim Dawson
    Isle of Mull, Scotland


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts