根据使用php提交的值创建动态字符串

时间:2014-10-24 05:26:16

标签: php

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

如果用户输入field1并提交2。我正在尝试创建一个字符串为filed1 = 2& filed2 = 3

如果用户只输入field2和field3,则field2 = test& field3 = testing

基本上不附加空文件。如何才能在php?

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

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

2 个答案:

答案 0 :(得分:0)

试试这个:

$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
}

手册:

array_filter

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);
}

答案 1 :(得分:0)

$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
        }