基于动态密钥=>值的PhP关联错误数组

时间:2013-02-13 10:07:35

标签: php arrays dynamic associative

这是我开始编写的一个类,用于通过注册表单向我的数据库添加新用户。一切都运行良好,直到我尝试进行后端检查,看看是否没有提供所需的值。这是代码......

class User
{
//Basic Login variables
private $uName;
private $pWord;
private $cpWord;
private $shaPass;

//Account info vars
private $fName;
private $lName;
private $email;
private $confEmail;
private $mPhone;
private $hPhone;

//Trading info vars
private $trName;
private $phone; //Defaults to home phone, or cell, if no home number specified.
private $fax;
private $web;

//Home Address vars
private $h_addr1;
private $h_addr2;
private $h_city;
private $h_state;
private $h_zip;

//Postal Address vars
private $p_addr1;
private $p_addr2;
private $p_city;
private $p_state;
private $p_zip;

private $not_required_vars;
//Post name collection
private $post_coll;
//Error collection
private $errors;

public function User()
{       
    $this->not_required_vars = array('fax', 'web');
    $this->post_coll = array('uName', 'pWord', 'cpWord', 'fName', 'lName', 'email', 'confEmail', 'dob', 'mPhone', 'hPhone', 'trName', 'phone', 'fax', 'web', 'h_addr1', 'h_addr2', 'h_city', 'h_state', 'h_zip', 'p_addr1', 'p_addr2', 'p_city', 'p_state', 'p_zip');
    //print_r($_POST);

    foreach($this->post_coll as $index)
    {
        if(isset($_POST[$index]) && (!empty($_POST[$index])))
        {
            //echo $index . '<br />';
            $this->{$index} = $_POST[$index];
        }else
        {
            foreach($this->not_required_vars as $not_req)
            {
                if($index != $not_req)
                {
                    //echo $index . '<br />';
                    $this->errors = array();

                    $this->errors[] = array($index=>'This field is required');
                    break;
                    //header('location: '.$_SERVER['PHP_SELF'].'?page='. $_GET['page'] . '&error=1');
                }
            }
        }

    }
    print_r($this->errors);
}

让我试着通过解释上面的内容来节省你的时间......我有一个名为'post_coll'的$ _POST索引字符串数组。然后我让我的foreach循环遍历每个字符串检查是否在$ _POST数组中设置了该字符串,如果不是,我检查它是否是必需值。如果它确实是一个必需的值,我想创建一个带有字符串的关联数组(例如'uName')作为数组中的键,当我将其重定向回时,该值的值类似于“此字段是必需的”我的表格我可以从班上得到错误,并在表格上的适当位置显示。

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

$this->errors[] = array($index=>'This field is required');

这一行看起来像是它的创建和数组数组

你要找的不是这样吗?

$this->errors[$index] = 'This field is required';