Skip to content

Instantly share code, notes, and snippets.

@carlynorama
Created November 14, 2011 17:54
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 carlynorama/1364599 to your computer and use it in GitHub Desktop.
Save carlynorama/1364599 to your computer and use it in GitHub Desktop.
stdClass Object into flat array
//bust the objects down to arrays
function objectToArray($result)
{
$array = array();
foreach ($result as $key=>$value) {
if (is_object($value)) {
$array[$key]=objectToArray($value);
}
elseif (is_array($value)) {
$array[$key]=objectToArray($value);
}
else {
$array[$key]=$value;
}
}
return $array;
}
// turn an array-of-arrays with a bottom key of 'ID' to a list
function flattenObjectByID($object)
{
$idlist = array();
foreach ($object as $val) {
$myid = $val['ID']; // does this work?
array_push($idlist, $myid);
}
return $idlist;
}
// turn an array-of-arrays into an array of the values of the bottom key $bk
function flattenObjectByKey($object, $bk)
{
$idlist = array();
foreach ($object as $val) {
$myid = $val[$bk]; // does this work?
array_push($idlist, $myid);
}
return $idlist;
}
//$stdObjectwithBottomKeyID might come from a sql statement like
//"SELECT ID FROM wp_posts WHERE post_parent = $post->ID AND post_type='page'"
$array = objectToArray($stdObjectwithBottomKeyID);
$flattenedbyID = flattenObjectByID($array);
$flattenedbyPassedKey = flattenObjectByKey($array, 'ID');
print_r($stdObjectwithBottomKeyID);
print_r($flattenedbyID);
print_r($flattened2);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment