Reputation: 8684
I have this JSON incoming into a controller method:
$data = $request->get('data');
// output
// [{"key": " Needs Trim ", "value": "Two"}, {"key": "", "value": "empty key"}]
It's an array of objects and I need to to clean it before inserting it to the DB table:
So the final result after the cleaning of the array of objects would look like this:
[{"key": "Needs Trim", "value": "Two"}]
I looked into laravel's array helper functions but I can't seem to get the output I need after hours spent on this. It expects a different format, and their examples show nested arrays as opposed to objects...
Any idea how to accomplish this?
Upvotes: 0
Views: 833
Reputation: 2927
Give this a shot:
$data = json_decode('[{"key": " Needs Trim ", "value": "Two"}, {"key": "", "value": "empty key"}]');
foreach ( $data as $key => $el ) {
foreach ( $el as $valKey => $val ) {
if ( empty($val) ) {
unset($data[$key]);
} else {
$el->$valKey = trim($val);
}
}
}
Upvotes: 1