0

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:

  • Trim leading/trailing spaces in key/value (first object)
  • Remove any object with an empty key or value from array (second object)

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?

1
  • You could just use array_map() with a custom handle function, right? Check the manual, plenty of examples thete. Commented Aug 18, 2016 at 20:23

1 Answer 1

1

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);
        }
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

This works, I'll just keep the question open a little longer to see if there is a solution that does not involve a nested foreach :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.