skip to Main Content

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?

2

Answers


  1. This solution splits apart the values based on underscores and then joins them back together as nested values based on the category/key. Note that this doesn’t check for items that don’t have a "prefix".

    <?php
    $columns = ["campaign_start_time", "campaign_end_time", "campaign_id", "campaign_budget", "adset_name", "ad_name"];
    
    $criteria = [];
    foreach( $columns as $column ){
        $pieces = explode('_',$column);
        $category = array_shift($pieces);
        
        if( !isset($criteria[$category]) ){
            $criteria[$category] = [];
        }
        
        $criteria[$category][] = implode('_', $pieces);
    }
    
    $queryPieces = [];
    foreach($criteria as $category => $values){
        $queryPieces[] = $category.'{'.implode(', ', $values).'}';
    }
    
    $query = implode(', ', $queryPieces);
    
    Login or Signup to reply.
  2. 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];
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search