Question

I am having trouble getting associative names of my $_errors array right.

$item1 = 'password';
$item2 = 'firstname';

$this->addError(array($item1 => 'required'))
$this->addError(array($item2 => 'required'))

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

public function error($item) {
    return array_search($item, $this->_errors);
}

When I do a print_r() on $_errors I get:

Array
(
    [0] => Array
        (
            [password] => required
        )
    [1] => Array
        (
            [firstname] => required
        )
)

But I need it to be:

Array
(
    [password] => required
    [firstname] => required
)

So I can call 'password' like so $this->_errors['password'];

Était-ce utile?

La solution

Simply change your functions accordingly:

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

$this->addError($item1, 'required');
$this->addError($item2, 'required');

Of course this scheme will not allow you to track multiple errors for the same element at the same time; if you need to do that you have to rethink your desired result.

Autres conseils

Use a list() construct to break the array into key-value pair and then subject it to your $this->errors[] array variable.

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

to

private function addError($error) {
    list($a,$b) = each($error);    //<--------- Add the list() here
    $this->_errors[$a] = $b; //<--------- Map those variables to your array 
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top