Skip to content

Instantly share code, notes, and snippets.

@appinteractive
Created January 20, 2016 09:03
Show Gist options
  • Select an option

  • Save appinteractive/67f3517ea76e3ab03cbd to your computer and use it in GitHub Desktop.

Select an option

Save appinteractive/67f3517ea76e3ab03cbd to your computer and use it in GitHub Desktop.
<?php
/**
* Class FromArray
* @author : Grzegorz Leoniec <[email protected]>
* @datetime: 14.01.16 14:31
*/
namespace Traits;
trait FromArray
{
/**
* set recursive property values from array
*
* @param array $data
* @return bool
*/
public function fromArray($data)
{
$updated = false;
foreach ($data as $key => &$value) {
if(property_exists($this, $key)) {
$this->setValue($key, $value, $this);
$updated = true;
}
}
return $updated;
}
/**
* set recursive values
*
* @param string $key
* @param $value
* @param $root
*/
private function setValue($key, &$value, &$root)
{
if (is_array($root)) {
$r = &$root[$key];
} else {
$r = &$root->$key;
}
if (is_array($value)) {
foreach ($value as $k => &$v) {
$this->setValue($k, $v, $r);
}
return;
}
$r = $value;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment