php - Iterate over object properties with keys from second array -
i call foreach loop on object , iterate on $this->_values
, keys present in $this->_allowedfields
.
1) $this->_values
can contain data not $this->_allowedfields
, should excluded foreach.
2) $this->_allowedfields
will contain keys not in $this->_values
, still need include step in foreach loop.
how can achieve this?
i have set class implement iterator , can call foreach loop on object's _values array, so:
foreach($object $key => $value) { // stuff }
solution
found solution myself below when implementing iterator interface.
public function rewind() { reset($this->_allowedfields); } public function current() { $key = current($this->_allowedfields); return $this->_values[$key]; } public function key() { $key = current($this->_allowedfields); return $key; } public function next() { next($this->_allowedfields); $key = current($this->_allowedfields); return $this->$this->_values[$key]; } public function valid() { $key = current($this->_allowedfields); $var = ($key !== null && $key !== false); return $var; }
if understood u correct, than: can't check values or fields? it's simple!
1) way
foreach($objects $key => $object){ foreach($object->_allowfields $allowfield){ if(isset($object->_values[$allowfield])){ echo $object->_values[$allowfield]; }else{ echo "sorry, field empty"; } }
}
2) way #2
foreach($objects $key => $object){ $allowedfields = $object->_allowfields; foreach($object->_values $key => $value){ if(in_array($key, $allowedfields)){ // field allowed }else{ // field not allowed } }}
Comments
Post a Comment