How to Remove a Key from an Object Not Array in Laravel

Laravel - Removing object inside of array based on key value - array_filter

if i understood u right , u want to rearrange the array after u do your logic plus keeping the structure , i would suggest you to use array_values

$new_data= array_values($data);

and if u got an error that its not an array although i doubt that just use the toArray() method

$new_data= array_values($data->toArray());

Laravel collection how to remove a specific key from all items?

$collection = $collection->map(function ($item) {
return array_only($item, ['id', 'name']);
});

Laravel- How to Remove a key from collection?

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;
}

Is it possible to delete an object's property in PHP?

unset($a->new_property);

This works for array elements, variables, and object attributes.

Example:

$a = new stdClass();

$a->new_property = 'foo';
var_export($a); // -> stdClass::__set_state(array('new_property' => 'foo'))

unset($a->new_property);
var_export($a); // -> stdClass::__set_state(array())

Laravel use toArray to add object to array and remove key

Use the values method of the Collection, similar to array_values:

$new = $message->values();

Assuming $message is the Collection holding the result of the unique call.

Laravel 6.x Docs - Collections - Available Methods - values

How to unset (remove) a collection element after fetching it?

You would want to use ->forget()

$collection->forget($key);

Link to the forget method documentation

Laravel Eloquent Collection remove item from Collection if exist in array

Instead of checking if the id is contained in the collection, you can just filter it with reject() directly

foreach ($this->verwendung as $item) {
$this->partsClient->reject(function ($value, $key) use ($item) {
return $value->id == $item['id'];
});
}

Or simply

$verwendungCollection = collect($this->verwendung);

$idsToRemove = $verwendungCollection->pluck('id')->toArray();

$this->partsClient->reject(function ($value, $key) use ($item) {
return in_array($value->id, $idsToRemove);
});

Remove key-value from Json object without loop in PHP

unset($array['FIRST']['roles']);
unset($array['SECOND']['roles']);


Related Topics



Leave a reply



Submit