lithium\data\Collection::to()

public method

Converts a Collection object to another type of object, or a simple type such as an array. The supported values of $format depend on the format handlers registered in the static property Collection::$_formats. The Collection class comes with built-in support for array conversion, but other formats may be registered.

Once the appropriate handlers are registered, a Collection instance can be converted into any handler-supported format, i.e.:

$collection->to('json'); // returns a JSON string
$collection->to('xml'); // returns an XML string

Please note that Lithium does not ship with a default XML handler, but one can be configured easily.

Parameters

  • string $format

    By default the only supported value is 'array'. However, additional format handlers can be registered using the formats() method.

  • array $options

    Options for converting this collection:

    • 'internal' boolean: Indicates whether the current internal representation of the collection should be exported. Defaults to false, which uses the standard iterator interfaces. This is useful for exporting record sets, where records are lazy-loaded, and the collection must be iterated in order to fetch all objects.
    • 'indexed' boolean|null: Allows to control how converted data is keyed. When set to true will force indexed conversion of the collection (the default) even if the collection has a parent. When false will convert without indexing. Provide null as a value to this option to only index when the collection has no parent.

Returns

mixed

The object converted to the value specified in $format; usually an array or string.

Source

	public function to($format, array $options = []) {
		$defaults = ['internal' => false, 'indexed' => true, 'handlers' => []];
		$options += $defaults;

		$options['handlers'] += $this->_handlers;
		$this->offsetGet(null);

		$index = $options['indexed'] || ($options['indexed'] === null && $this->_parent === null);
		if (!$index) {
			$data = array_values($this->_data);
		} else {
			$data = $options['internal'] ? $this->_data : $this;
		}
		return $this->_to($format, $data, $options);
	}