Compare array php foreach loop -
i have 2 arrays , want create output array.
example array requirements title , subtitle field:
array ( [title] => array ( [required] => 1 [minlength] => 2 [maxlength] => 50 ) [subtitle] => array ( [required] => 1 [minlength] => 2 [maxlength] => 55 ) )
post array after post s:
array ( [title] => [subtitle] => s )
example output array:
array ( [title] => array ( [0] => field required [1] => must longer 2 ) [subtitle] => array ( [0] => must longer 2 ) )
how can generate such array foreach loop?
this have, wont work well. if leave title blank , subtitle 1 character gives 2 times field required. looks duplicated.
class forms_formvalidationfields { private $_required; private $_minlength; private $_maxlength; private $_alphanumeric; public $_errors; public function __construct($validate, $posts) { array_pop($posts); $posts = array_slice($posts,1); foreach ( $posts $postname => $postvalue) { foreach( $validate[$postname] $key => $rulevalue ){ $set = 'set'.ucfirst($key); $get = 'get'.ucfirst($key); $this->$set( $postvalue , $rulevalue); if( $this->$get() != '' || $this->$get() != null) { $test[$postname][] .= $this->$get(); } } } $this->_errors = $test; } public function setvalidation(){ return $this->_errors; } public function getrequired() { return $this->_required; } public function setrequired($value, $rulevalue) { if (empty($value) && $rulevalue == true) { $this->_required = 'this field required'; } } public function getminlength() { return $this->_minlength; } public function setminlength($value, $rulevalue) { if (strlen($value) < $rulevalue) { $this->_minlength = ' must longer than' . $rulevalue . ''; } } public function getmaxlength() { return $this->_maxlength; } public function setmaxlength($value, $rulevalue) { if (strlen($value) > $rulevalue) { $this->_maxlength = 'must shorter than' . $rulevalue . ''; } } }
here go:
<?php $required = array( 'this field not required', 'this field required' ); $length = 'requires more {less} less {more}'; $needs = array( 'title' => array( 'required' => 1, 'minlength' => 2, 'maxlength' => 50, ), 'subtitle' => array( 'required' => 1, 'minlength' => 2, 'maxlength' => 55 ) ); $new_needs = array(); foreach($needs $key => $value) // loop on array { $new_needs[$key][] = $required[$value['required']]; $new_needs[$key][] = str_replace( array('{more}', '{less}'), array($value['maxlength'], $value['minlength']), $length ); } foreach($_post $key => $value) { if(empty($value)) { echo $new_needs[$key][0]; } if(strlen($value) > $needs[$key]['maxlength'] || strlen($value) < $needs[$key]['minlength']) echo $new_needs[$key][1]; }
should pretty self explanatory if read on it.
result:
array ( [title] => array ( [0] => field required [1] => requires more 2 less 50 ) [subtitle] => array ( [0] => field required [1] => requires more 2 less 55 ) )
Comments
Post a Comment