Ben Parsell Ben Parsell - 3 months ago 6
PHP Question

Grabbing the value of the parent key when using a foreach loop on an object in PHP?

So this is a bit goofy, but I need this for a logic gate. I have an object, that when dumped, looks like so:

object(stdClass)#925 (5) {
["31"]=> object(stdClass)#1180 (4) { ["price"]=> string(3) "6.5" ["finalPrice"]=> string(3) "6.5" ["tierpricing"]=> string(1) "0" ["has_image"]=> bool(true) }
["32"]=> object(stdClass)#1174 (4) { ["price"]=> string(4) "10.5" ["finalPrice"]=> string(4) "10.5" ["tierpricing"]=> string(1) "0" ["has_image"]=> bool(true) }
["36"]=> object(stdClass)#1331 (4) { ["price"]=> string(4) "18.5" ["finalPrice"]=> string(4) "18.5" ["tierpricing"]=> string(1) "0" ["has_image"]=> bool(true) }
["255"]=> object(stdClass)#1094 (4) { ["price"]=> string(4) "23.5" ["finalPrice"]=> string(4) "23.5" ["tierpricing"]=> string(1) "0" ["has_image"]=> bool(true) }
["1066"]=> object(stdClass)#1117 (4) { ["price"]=> string(5) "84.95" ["finalPrice"]=> string(5) "84.95" ["tierpricing"]=> string(1) "0" ["has_image"]=> bool(true) }
}


I then need to loop through with a foreach loop, where my var_dump now will look like so:

object(stdClass)#1180 (4) { ["price"]=> string(3) "6.5" ["finalPrice"]=> string(3) "6.5" ["tierpricing"]=> string(1) "0" ["has_image"]=> bool(true) }
object(stdClass)#1174 (4) { ["price"]=> string(4) "10.5" ["finalPrice"]=> string(4) "10.5" ["tierpricing"]=> string(1) "0" ["has_image"]=> bool(true) }
object(stdClass)#1331 (4) { ["price"]=> string(4) "18.5" ["finalPrice"]=> string(4) "18.5" ["tierpricing"]=> string(1) "0" ["has_image"]=> bool(true) }
object(stdClass)#1094 (4) { ["price"]=> string(4) "23.5" ["finalPrice"]=> string(4) "23.5" ["tierpricing"]=> string(1) "0" ["has_image"]=> bool(true) }
object(stdClass)#1117 (4) { ["price"]=> string(5) "84.95" ["finalPrice"]=> string(5) "84.95" ["tierpricing"]=> string(1) "0" ["has_image"]=> bool(true) }


This is, of course, respective, and I'm trying to see if I can grab onto those parent values (31, 32, 36, 255, 1066) while in the foreach iteration. Is this possible in anyway?

hsz hsz
Answer

Those values you are looking for are the keys. Try with:

foreach ($yourData as $key => $object) {
  var_dump($key);
  var_dump($object);
}
Comments