0

I have an object which contains keys with values that are objects, and inside of those objects there are another objects as value for one of the keys. I have been able to get a specific value from the deep nested object I need by doing 4 loops, but I was wondering if there is a better way of doing so. Here is the object I have:

{
  record1: {
    key1: value1,
    key2: value2,
    key3: {
      key_x1: value_x1,
      key_x2: value_x2,
      key_x3: value_x3
    }
  }
  record2: {
    key1: value1,
    key2: value2,
    key3: {
      key_x1: value_x1,
      key_x2: value_x2,
      key_x3: value_x3
    }
  }
}

So, for each record (record1 and record2 etc.) I need to pull out the value from key_x1 and store it in an array. Any ideas on how to accomplish this without having 4 foreach loops?

EDIT: Here is what I have which works, just looks ugly:

   $mainObject
   $a = [];
   $dateArray = [];

    foreach ($mainObject as $individualOb) {
        $dates = $individualOb->getDate();
        $a[] = $dates;
    }

    if (empty($a)) {
        return true;
    } else {
        foreach ($a as $date) {
            foreach ($date as $key => $value) {
                if ($key == 'date') {
                    $dateArray[] = $value;
                }
            }
        }
        foreach ($dateArray as $value) {
            if(strtotime($value) < strtotime('-1 year') ) {
                return true;
            }
        }
    }

1 Answers1

0

You could nest the loops like this:

foreach ($mainObject as $individualOb) {
    foreach ($individualOb->getDate() as $key => $value) {
        if ($key == 'date' && strtotime($value) < strtotime('-1 year') ) {
            return true;
        }
    }
}

I am not sure why you want to return true when there are no elements, as false seems more logical. Anyway you can do that test straight on $mainObject:

if (empty($mainObject)) {
    return true;
} else // ...etc.
trincot
  • 317,000
  • 35
  • 244
  • 286
  • ignore the returns for now. These loops are actually in a function which I am calling elsewhere. But, in terms of the snippet you posted, I original had tried nesting for each loops and it was writing out double of each wanted value. I think my problem was that I didn't use the key value pairing for the 2nd foreach loop. I will give this code a try and get back at you. :) – Tomislav Mladenovski Jul 31 '16 at 16:02
  • Well, if your code is not about returning false/true, then my answer might not be suitable. But then, please update your question with more relevant code. – trincot Jul 31 '16 at 16:06
  • Edit: just tried it and it works like a charm. You are a genius sir :) Edit 2: the mainObject ALWAYS has one key inside of it, but THAT key can be empty which I think I know how to go about solving now :) Once again, thank you! – Tomislav Mladenovski Jul 31 '16 at 16:30