开发者

multi-dimensional stdClass Object

I've got a rather large multidimensional stdClass Object being outputted from a json feed with PHP.

It goes about 8 or 9 steps deep and the data that I need is around 7 steps in.

I'm wondering if I can easily grab one of the entires instead of doing this:

echo $data->one->two->anotherone->g开发者_JAVA技巧ettinglong->omg->hereweare;

I'm saying this because the data structure may change over time.

Is this possible?


You could try to parse the object into an array and search the array for the wanted values, it just keeps looping through each level of the object.

function parseObjectArrayToArray($objectPassed, &$in_arr = array()) { 
    foreach($objectPassed as $element) {
        if(is_object($element) || is_array($element)) {
            parseObjectArrayToArray($element,$in_arr);
        } else {
            // XML is being passed, need to strip it
            $element = strip_tags($element); 

            // Trim whitespace
            $element = trim($element);

            // Push to array  
            if($element != '' && !in_array($element,$in_arr)) {                
                  $in_arr[] = $element;  
            } 
        }
    }
    return $in_arr;
}

How to call

$parsed_obj_arr = parseObjectArrayToArray($objectPassed);


Not without searching through whats probably inefficient. Json is a structured data object with the purpose of eliminating something like this.


If the datastructure can change, but doesn't very often, your best bet is to write a wrapper object so you will only have to change a path at a single point on change:

class MyDataWrapp {
   public $json;
   function __construct($jsonstring){
      $this->json = json_decode($jsonstring);
   }
   function getHereWeAre(){
       return $this->json->one->two->anotherone->gettinglong->omg->hereweare;
   }
}

If the datastructure changes dramatically and constantly, I'd json_decode as an array of arrays, and probably use RecursiveFilterIterator.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜