Created
November 14, 2011 17:54
-
-
Save carlynorama/1364599 to your computer and use it in GitHub Desktop.
stdClass Object into flat array
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
//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; | |
} |
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
//$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