Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
190 views
in Technique[技术] by (71.8m points)

PHP convert columns to query

I have a table on the frontend, where the user can choose what types of columns he wants. After submitting the form I get the array with selected columns. For instance the user select following columns:

$columns = ["campaign_start_time", "campiagn_end_time", "campaign_id", "campaign_budget", "adset_name", "ad_name"]

Now I have to make the request to the facebook api, but facebook api only request query in form:

 $query = "campaign{start_time, end_time, id, budget}, adset{name}, ad{name}"

Here is my question, what is the best way to convert $columns to $query in PHP language?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you can construct your submitted data to be in this form:

Array
(
    [campaign] => Array
        (
            [0] => start_time
            [1] => end_time
            [2] => id
            [3] => budget
        )
    [adset] => Array
        (
            [0] => name
        )
    [ad] => Array
        (
            [0] => name
        )
)

Maybe using inputs or other constructs such as:

name="campaign[]" value="start_time"
name="campaign[]" value="end_time"

Then looping and building the query with the keys and values will do it:

foreach($columns as $key => $val) {
    $query[] = $key . '{' . implode(',', $val) . '}';
}
$query = implode(',', $query);

Otherwise you'll need to parse it to get what you need first, then execute the loop above using $result instead:

foreach($columns as $val) {
    preg_match('/^([^_]+)_(.*)/', $val, $match);
    $result[$match[1]][] = $match[2];
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...