...

View Full Version : Resolved Accessing the second level of a Multidimensional array



Chris Hick
01-14-2012, 07:53 AM
Ok, so I have a multidimensional array:



$fields = array(
'username' =>
array("isEmpty","checkUsername"),
'password' =>
array("isEmpty","checkPassword"),
);



And what I am trying to do is get the second array and do a foreach with them. I am trying to create my formValidation class. The idea is that I want to be able to list the fields in an array then rules in an array within it.

Then, when I call my validation class its construct method:


function __construct($fields) {
$this->getRules($fields);
if(!$this->isValid) {
return $this->errors;
}
}

which calls a method getRules(); this is the get rules method:


private function getRules($fields) {
foreach ($fields as $field) {
if(array_key_exists($field, $_POST)){
foreach ($field as $rule) {
if(method_exists($this,$rule)) {
$this->$rule($field);
}else {
$this->errors["method"] = "This rule does not exist";
}
}
} else {
$this->errors["exist"] = "This field does not exist";
}
}
return $this->errors;
}


which calls the methods of the rules.

But this isn't exactly working. I'm getting the error=> array_key_exists:The first argument should be either a string or an integer

Chris Hick
01-14-2012, 03:25 PM
I figured out the solution to this problem. :) Definitely took me some thinking, but here is the solution.


private function getRules($fields) {
foreach ($fields as $field=>$rules) {
if(array_key_exists($field, $_POST)){
foreach ($rules as $rule) {
if(method_exists($this,$rule)) {
$this->$rule($field);
}else {
$this->errors["method"] = "This rule does not exist";
}
}
} else {
$this->errors["exist"] = "This field does not exist";
}
}
return $this->errors;
}



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum