Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel- How to Remove a key from collection?

I have data as below:

[
        {
            "id": "3",
            "title": "Boruto's Photo",
            "is_lottery": 1,
            "price": 10
        },
        {
            "id": "4",
            "title": "Misuki's Photo",
            "is_lottery": 0,
            "price": 20
        }

    ]

I want to filter which is is_lottery == false remove the price key from this collection. The output is:

[
        {
            "id": "3",
            "title": "Boruto's Photo",
            "is_lottery": 1,
            "price": 10
        },
        {
            "id": "4",
            "title": "Misuki's Photo",
            "is_lottery": 0,
        }

    ]
like image 796
Sok Chanty Avatar asked Dec 30 '25 12:12

Sok Chanty


2 Answers

You can do this

$json = '[
   {
       "id": "3",
       "title": "Boruto\'s Photo",
       "is_lottery": 1,
       "price": 10
    },
    {
       "id": "3",
       "title": "Misuki\'s Photo",
       "is_lottery": 0,
       "price": 20
   }

]';

$filtered = collect(json_decode($json, true))->map(function ($array) {
   if (!$array['is_lottery']) {
       unset($array['price']);
   }
   return $array;
});

For native PHP you can do

$data = json_decode($json, true);

foreach ($data as $index => $array) {
   if (!$array['is_lottery']) {
       unset($array['price']);
   }
   $data[$index] = $array;
}
like image 90
mmabdelgawad Avatar answered Jan 01 '26 11:01

mmabdelgawad


$json = [
        {
            "id": "3",
            "title": "Boruto's Photo",
            "is_lottery": 1,
            "price": 10
        },
        {
            "id": "4",
            "title": "Misuki's Photo",
            "is_lottery": 0,
            "price": 20
        }

    ];

$filtered = collect(json_decode($json))->map(function($value, $key) {
    if (!$value['is_lottery']) {
      Arr::except($value, 'price');
   }
   return $value;
});

like image 45
Kingsley Uchenna Avatar answered Jan 01 '26 11:01

Kingsley Uchenna



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!