Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing Keys In Associative Array Not Working

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?

like image 776
nmock Avatar asked May 16 '26 02:05

nmock


1 Answers

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]);
like image 166
sberry Avatar answered May 17 '26 17:05

sberry