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
$dataobject. You can fix it one of two ways. Either access by reference or update yourunsetto act on the original$dataobject instead.Using reference:
Unsetting from
$data