I try this code (via Fractal) to get result:
public static function doIt($array, $transformer)
{
$manager = new Manager();
$serializer = new \League\Fractal\Serializer\ArraySerializer();
$manager->setSerializer($serializer);
if ($array instanceof Collection) {
$resource = new FractalCollection($array, new $transformer);
} else {
$resource = new FractalItem($array, new $transformer);
}
return $manager->createData( $resource )->toArray();
}
As you look, I added
$serializer = new \League\Fractal\Serializer\ArraySerializer();
$manager->setSerializer($serializer);
to remove 'data' attribute from result array.
array:3 [▼
"key" => 1
"title" => "First Level Title"
"childrens" => array:1 [▼
"data" => array:16 [▼ ←-------- it need remove!
0 => array:2 [▼
"key" => 2
"title" => "Children Title"
]
1 => array:2 [▶]
2 => array:2 [▶]
3 => array:2 [▶]
]
]
]
It's well work, but only for first level of array. How to do, for this to work for all nested arrays?
I solved this problem. You need create own Serializer extends of DataArraySerializer. It have three methods and in each of them need change return values to this:
use League\Fractal\Serializer\DataArraySerializer;
class Serializer extends DataArraySerializer
{
/**
* Serialize a collection.
*
* @param string $resourceKey
* @param array $data
*
* @return array
*/
public function collection($resourceKey, array $data)
{
return $data;
}
/**
* Serialize an item.
*
* @param string $resourceKey
* @param array $data
*
* @return array
*/
public function item($resourceKey, array $data)
{
return $data;
}
/**
* Serialize null resource.
*
* @return array
*/
public function null()
{
return [];
}
}
Now we just set this serializer to the Manager instance we use.
$manager = new Manager();
$manager->setSerializer(new Serializer());
You can use current() method, I hope it will solve your problem.
Example:
return current($manager->createData( $resource )->toArray());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With