Skip to content

Instantly share code, notes, and snippets.

@mrgarymartin
Last active May 4, 2016 17:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrgarymartin/92b5b43b85625f810a4d32d6194e9a8c to your computer and use it in GitHub Desktop.
Save mrgarymartin/92b5b43b85625f810a4d32d6194e9a8c to your computer and use it in GitHub Desktop.
Convert Array to Object Function
<?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