-1

Given an array, in which each index there are certain key value pairs, how do I select certain key value pairs and reject the others.

$channels = Channel::get()->toArray();

This will yield the following Array:

"channels": [
    {
        "id": 1,
        "name": "Info Release",
        "slug": "info-release",
        "desc": "Contains blah blah.",
        "access_level": "0",
        "created_at": "2018-12-02 01:23:50",
        "updated_at": "2018-12-05 07:54:41"
    },
    {
        "id": 11,
        "name": "Casual News",
        "slug": "casual-news",
        "desc": "Contains blah blah.",
        "access_level": "0",
        "created_at": "2018-12-05 05:34:50",
        "updated_at": "2018-12-05 07:54:32"
    },
    {
        "id": 12,
        "name": "haha",
        "slug": "haha",
        "desc": "Contains blah blah.",
        "access_level": "0",
        "created_at": "2018-12-29 23:27:16",
        "updated_at": "2018-12-29 23:27:16"
    }
],

What is the best way to turn that array into this:

"channels": [
    {
        "id": 1,
        "name": "Information Release",
        "slug": "information-release",
    },
    {
        "id": 11,
        "name": "Casual News",
        "slug": "casual-news",
    },
    {
        "id": 12,
        "name": "haha",
        "slug": "haha",
    }
],

So that if I write

$channels[0]->id

it will spit out 1

Ash
  • 25
  • 8
  • can't you just ignore them? –  Jul 02 '19 at 00:48
  • @tim It's being passed to the frontend via an api endpoint and I wouldn't want that data to be local. – Ash Jul 02 '19 at 01:35
  • 1
    Possible duplicate of [PHP: remove element from multidimensional array (by key) using foreach](https://stackoverflow.com/questions/27482851/php-remove-element-from-multidimensional-array-by-key-using-foreach) – rh16 Jul 02 '19 at 01:58

1 Answers1

0

Can You try this

$viewFileds = ['id', 'name', 'slug'];

$channels = Channel::get()
                    ->map(function ($each) use ($viewFileds) {
                        return Arr::only($each, $viewFileds);
                    }); 

It will return the new Collection by Only the field enabled in the $viewFileds

Hope it helps

ManojKiran A
  • 5,896
  • 4
  • 30
  • 43