Last active
May 4, 2016 17:47
-
-
Save mrgarymartin/92b5b43b85625f810a4d32d6194e9a8c to your computer and use it in GitHub Desktop.
Convert Array to Object Function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Convert Arrays to Class Objects | |
* Author: Gary Martin | |
* Date: 5/2/2016 | |
* | |
* Description: This Converts arrays to Objects that have getters and setters preventing. | |
* If the $key is not defined in the model it gets skipped. | |
* The model must have a getAttributes function that returns the attributes in a array. | |
* This code will reduce that to check if its in the array. | |
*/ | |
function convertArrayToObject($array, $model) | |
{ | |
/** @var \shortcodes\models\BaseModel $object */ | |
$object = new $model; | |
$attibrutes = $object->attributes; | |
$attArray = []; | |
foreach ($attibrutes as $k => $v) { | |
$attArray = array_merge([$k], $attArray); | |
} | |
array_reduce($attArray, 'array_merge', array()); | |
foreach ($array as $key => $value) { | |
if (is_array($value)) { | |
if (count($value) === 1) { | |
$value = $value[0]; | |
} else { | |
// This was a thought to create a sub modeil of the items.. might not be needed. | |
// $value = convertArrayToObject($value, $model); | |
} | |
} | |
if (in_array($key, $attArray)) { | |
error_log('Is in Array'); | |
$object->$key = $value; | |
} else { | |
error_log('NOT in Array'); | |
} | |
} | |
return $object; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment