I am trying to retain only certain keys, and remove the rest from an external API. I have an array (http://pastebin.com/vU8T4y7h), "data" containing the objects:
foreach ($data as $media) {
foreach (array_keys($media) as $media_key) {
if ($media_key!=="created_time" && $media_key!=="likes" && $media_key!=="images" && $media_key!=="id") {
unset($media[$media_key]);
}
}
}
In this case, I am trying to only keep the created_time, likes, images, and id keys, however, the above code isn't working. Any ideas as to why? Any other elegant solutions to achieve the same thing?
The reason this isn't working is because you aren't unsetting from the original $data object. You can fix it one of two ways. Either access by reference or update your unset to act on the original $data object instead.
Using reference:
foreach($data as &$media) {
Unsetting from $data
unset($data[$media][$media_key]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With