在嵌套数组中获取数组键值

时间:2014-02-11 00:07:18

标签: php arrays oop pdo

我需要获取一个数组值,其键名为"name",但我似乎无法弄明白。当用户没有填写字段并且我希望它更具体时,我显示错误。在我输出错误的情况下,页面显示fname needs to be filled,但是在我的脚本中的一个数组中,检查表单中所需的东西,我列出了一个名称,我希望它显示First Name needs to be filled。我的代码如下。

<?php
require_once 'Assets/Scripts/Core/Init.php';

if(Input::exists()){
    if(Token::check(Input::get('token'))){
        $Validate = new Validate();
        $Validation = $Validate->check($_POST, array(
            'fname' => array(
                'name' => 'First Name',
                'required' => true,
                'min' => '2',
                'max' => '16',
                'alpha' => true
            ),
            'lname' => array(
                'name' => 'Last Name',
                'required' => true,
                'min' => '2',
                'max' => '16',
                'alpha' => true
            ),
            'email' => array(
                'name' => 'E-Mail',
                'required' => true,
                'max' => '128',
                'email' => true,
                'unique' => 'users'
            ),
            'password' => array(
                'name' => 'Password',
                'required' => true
            ),
            'pn' => array(
                'name' => 'Phone Number',
                'required' => true,
                'max' => '10',
                'num' => true
            ),
            'student_id' => array(
                'name' => 'School ID',
                'required' => true,
                'max' => '10',
                'num' => true
            )
        ));

        if($Validate->passed()){
            $user = new User();
            $salt = Hash::salt(32);

            try {
                $user->create('users', array(
                    'email' => Input::get('email'),
                    'password' => Hash::make(Input::get('password'), $salt),
                    'salt' => $salt,
                    'fname' => Input::get('fname'),
                    'lname' => Input::get('lname'),
                    'phone' => Input::get('pn'),
                    'student_id' => Input::get('student_id'),
                    'ip' => $_SERVER['REMOTE_ADDR'],
                    'date' => date('Y-m-d H:i:s'),
                    'usergroup' => 1
                ));
            } catch(Exception $e) {
                die($e->getMessage());
            }
        }
        else {
            echo print_r($Validate->errors());
        }
    }
}

我的验证课程:

<?php
class Validate {
    private $_passed = false,
            $_errors = array(),
            $_db = null;

    public function __construct(){
        $this->_db = DB::getInstance();
    }

    public function check($data, $items = array()){
        foreach($items as $item => $rules){
            foreach($rules as $rule => $rule_value){
                trim($value = $data[$item]);
                $item = escape($item);

                if($rule === 'required' && empty($value)){
                    $this->addError("{$item} is required");
                }
                else if(!empty($value)){
                    switch($rule){
                        case 'min':
                            if(strlen($value) < $rule_value){
                                $this->addError("{$item} must be a minimum of {$rule_value} characters.");
                            }
                        break;
                        case 'max':
                            if(strlen($value) > $rule_value){
                                $this->addError("{$item} must be a maximum of {$rule_value} characters.");
                            }
                        break;
                        case 'matches':
                            if($value != $data[$rule_value]){
                                $this->addError("{$rule_value} must match {$item}");
                            }
                        break;
                        case 'unique':
                            $check = $this->_db->get($rule_value, array($item, '=', $value));
                            if($check->count()){
                                $this->addError("{$item} already exists.");
                            }
                        break;
                        case 'email':
                            if(!filter_var($value, FILTER_VALIDATE_EMAIL)) {
                                $this->addError("{$item} is not a valid email.");
                            }
                        break;
                        case 'num':
                            if(!is_numeric($value)){
                                $this->addError("{$item} can only contain numbers.");
                            }
                        break;
                        case 'alpha':
                            if(!ctype_alpha($value))
                            {
                                $this->addError("{$item} can only contain letters.");
                            }
                        break;
                    }
                }
            }
        }

        if(empty($this->_errors)){
            $this->_passed = true;
        }

        return $this;
    }

    private function addError($error){
        $this->_errors[] = $error;
    }

    public function errors(){
        return $this->_errors;
    }

    public function passed(){
        return $this->_passed;
    }
}

输入类:

<?php
class Input {
    public static function exists($type = 'post'){
        switch($type) {
            case 'post':
                return (!empty($_POST)) ? true : false;
            break;
            case 'get':
                return (!empty($_POST)) ? true : false;
            break;
            default:
                return false;
            break;
        }
    }

    public static function get($item){
        if(isset($_POST[$item])){
            return $_POST[$item];
        }
        elseif(isset($_GET[$item])){
            return $_GET[$item];
        }
        else {
            return '';
        }
    }
}

我需要能够输出'name'数组中具有键fname的值。在这种情况下,它应输出First Name

2 个答案:

答案 0 :(得分:1)

您需要将"is required"部分移出rules循环,以便您可以轻松地使用它。然后,您还可以轻松引用"pretty"名称。

只需将Validate::check功能更改为:

即可
public function check($data, $items = array()){
    foreach($items as $item => $rules){
        // check required earlier (moved to here)
        if(isset($rules['required']) && $rules['required'] && empty($data[$item])) {
           $this->addError($rules['name'] . " is required");
        }

请注意,我将其更改为使用$rules['name']而不是$item,因此您获得"pretty"名称。

        foreach($rules as $rule => $rule_value){
            trim($value = $data[$item]);
            $item = escape($item);

            // removed the required check here

            else if(!empty($value)){
                switch($rule){
                    case 'min':
                        if(strlen($value) < $rule_value){
                            $this->addError("{$item} must be a minimum of {$rule_value} characters.");
                        }
                    break;
                    case 'max':
                        if(strlen($value) > $rule_value){
                            $this->addError("{$item} must be a maximum of {$rule_value} characters.");
                        }
                    break;
                    case 'matches':
                        if($value != $data[$rule_value]){
                            $this->addError("{$rule_value} must match {$item}");
                        }
                    break;
                    case 'unique':
                        $check = $this->_db->get($rule_value, array($item, '=', $value));
                        if($check->count()){
                            $this->addError("{$item} already exists.");
                        }
                    break;
                    case 'email':
                        if(!filter_var($value, FILTER_VALIDATE_EMAIL)) {
                            $this->addError("{$item} is not a valid email.");
                        }
                    break;
                    case 'num':
                        if(!is_numeric($value)){
                            $this->addError("{$item} can only contain numbers.");
                        }
                    break;
                    case 'alpha':
                        if(!ctype_alpha($value))
                        {
                            $this->addError("{$item} can only contain letters.");
                        }
                    break;
                }
            }
        }
    }
}

答案 1 :(得分:0)

将$ item更改为$ rules ['name']

public function check($data, $items = array()){
    foreach($items as $item => $rules){
        foreach($rules as $rule => $rule_value){
            trim($value = $data[$item]);
            $item = escape($item);

            if($rule === 'required' && empty($value)){
                $this->addError("{$rules['name']} is required");
            }
            else if(!empty($value)){
                switch($rule){
                    case 'min':
                        if(strlen($value) < $rule_value){
                            $this->addError("{$item} must be a minimum of {$rule_value} characters.");
                        }
                    break;
                    case 'max':
                        if(strlen($value) > $rule_value){
                            $this->addError("{$item} must be a maximum of {$rule_value} characters.");
                        }
                    break;
                    case 'matches':
                        if($value != $data[$rule_value]){
                            $this->addError("{$rule_value} must match {$item}");
                        }
                    break;
                    case 'unique':
                        $check = $this->_db->get($rule_value, array($item, '=', $value));
                        if($check->count()){
                            $this->addError("{$item} already exists.");
                        }
                    break;
                    case 'email':
                        if(!filter_var($value, FILTER_VALIDATE_EMAIL)) {
                            $this->addError("{$item} is not a valid email.");
                        }
                    break;
                    case 'num':
                        if(!is_numeric($value)){
                            $this->addError("{$item} can only contain numbers.");
                        }
                    break;
                    case 'alpha':
                        if(!ctype_alpha($value))
                        {
                            $this->addError("{$item} can only contain letters.");
                        }
                    break;
                }
            }
        }
    }