基于使用php提交的值创建动态字符串


creating dynamic string based on values submitted using php

我的页面中大约有8个字段,例如:、filed1、filed2、field3等。

如果用户输入字段1和字段2;filed2=3

如果用户只输入字段2和字段3,则字段2=test&field3=测试

基本上不追加空文件。如何可能在php中?

我试过这样,但不是正确的方式

if($_POST['filed1']!='')
$append = $_POST['filed1'];
if($_POST['filed1']!='' && $_POST['filed2']!='')
$append = 'field1='.$_POST['filed1'].'&field2='.$_POST['filed2'];

试试这个:

$string = '';
if ('POST' == $_SERVER['REQUEST_METHOD'])
{
    $fields = array_filter($_POST); // filter array from empty values
    $string = http_build_query($fields); // build url query string same as your case
}

对于手册:

阵列滤波器

http_build_query

更新:

$string = '';
if ('POST' == $_SERVER['REQUEST_METHOD'])
{
    $wanted = array(
        'clientUrlpass' => '', 
        'clients'       => '', 
        'location'      => '', 
        'cmpt'          => '', 
        'datefirst'     => '', 
        'da‌​tesecond'    => ''
    );
    foreach($wanted as $key => &$value)
    {
        if (isset($_POST[$key]))
        {
            $value = trim($_POST[$key]);
        }
        if (!$value)
        {
            unset($wanted[$key]);
        }
    }   
        //this not needed while we already excluded empty values
        //$fields = array_filter($_POST);
    $string = http_build_query($wanted);
}
$arrayPost = array('clientId'=>$clients,
                            'locationIds'=> $location,
                            'personIds' =>$person,
                            'status'=>$status,
                            'competitor' =>$cmpt,
                            'startDate'=>$firstDate,
                            'endDate'=>$secondDate,
                            'sourceIds' => $source
                    );
            $fields = array_filter($arrayPost); // filter array from empty values
            $filterOutKeys = array('_search','nd','rows','page','sord');
            $filteredArr = array_diff_key( $fields, array_flip( $filterOutKeys ) );
            $stringToPass = http_build_query($filteredArr); // build url query string same as your case
        }