lithium\util\Collection::toArray PHP Method

toArray() public static method

Exports a Collection instance to an array. Used by Collection::to().
public static toArray ( mixed $data, array $options = [] ) : array
$data mixed Either a `Collection` instance, or an array representing a `Collection`'s internal state.
$options array Options used when converting `$data` to an array: - `'handlers'` _array_: An array where the keys are fully-namespaced class names, and the values are closures that take an instance of the class as a parameter, and return an array or scalar value that the instance represents.
return array Returns the value of `$data` as a pure PHP array, recursively converting all sub-objects and other values to their closest array or scalar equivalents.
    public static function toArray($data, array $options = array())
    {
        $defaults = array('handlers' => array());
        $options += $defaults;
        $result = array();
        foreach ($data as $key => $item) {
            switch (true) {
                case is_array($item):
                    $result[$key] = static::toArray($item, $options);
                    break;
                case !is_object($item):
                    $result[$key] = $item;
                    break;
                case isset($options['handlers'][$class = get_class($item)]):
                    $result[$key] = $options['handlers'][$class]($item);
                    break;
                case method_exists($item, 'to'):
                    $result[$key] = $item->to('array', $options);
                    break;
                case $vars = get_object_vars($item):
                    $result[$key] = static::toArray($vars, $options);
                    break;
                case method_exists($item, '__toString'):
                    $result[$key] = (string) $item;
                    break;
                default:
                    $result[$key] = $item;
                    break;
            }
        }
        return $result;
    }

Usage Example

Example #1
0
	/**
	 * Adds conversions checks to ensure certain class types and embedded values are properly cast.
	 *
	 * @param string $format Currently only `array` is supported.
	 * @param array $options
	 * @return mixed
	 */
	public function to($format, array $options = array()) {
		$defaults = array('handlers' => array(
			'MongoId' => function($value) { return (string) $value; },
			'MongoDate' => function($value) { return $value->sec; }
		));

		if ($format == 'array') {
			$options += $defaults;
			return Collection::toArray($this->_data, $options);
		}
		return parent::to($format, $options);
	}
All Usage Examples Of lithium\util\Collection::toArray