0

I'm having trouble creating a function on collection map with return values.

public function getCollectionFakeId($collection, $fieldNames){

        $optimus = $this->optimus;

        $result = $collection->map(function($item, $key) use ($optimus, $fieldNames) {

                return [
                    $fieldNames[0] =>$optimus->encode($item->id),
                    $fieldNames[1] => $item->lastname
                ];


        }) ;

        dd($result);
        return  json_decode(json_encode($result), FALSE);


    }

As you can see the return fieldNames[0] is being hardcoded. I don't know how many fieldNames it will received. I need to return those fieldnames with obfuscated Id. So basically The only changed is the Id. Here is the screenshot.

enter image description here

As you can see the fieldNames are just 2 but what if it becomes 5 or 6. I don't really know how many fieldNames they are going to pass in the parameter. How can I return it. Thanks.

Rbex
  • 1,519
  • 6
  • 24
  • 50

1 Answers1

0

In case someone will encounter this problem. Here is my solution...

public function getCollectionFakeId($collection, $fieldNames){

        $optimus = $this->optimus;

        $result = $collection->map(function($item, $key) use ($optimus, $fieldNames) {

                $mapFieldNames = array_map(function($v) use ($optimus, $item) {
                    if( $v == 'id'){
                        return $optimus->encode($item->id);
                    }
                    else{
                        return $v;
                    }
                }, $fieldNames);

               return $mapFieldNames;
        }) ;

        dd($result);
        return  json_decode(json_encode($result), FALSE);


    }

The result is the same. AWESOME!

Rbex
  • 1,519
  • 6
  • 24
  • 50