PHP code example of kozz / collection

1. Go to this page and download the library: Download kozz/collection library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

kozz / collection example snippets


    use Kozz\Components\Collection;
    $collection = new Collection();

        $traversable = new \ArrayIterator(range(1,1000));
        $collection = Collection::from($traversable);
    

        $mongo = new \MongoClient();
        $cursor = $mongo->selectDB('testDB')->selectCollection('testCollection')->find();
        $collection = new Collection($cursor);
    

    use Kozz\Components\Collection;
    
    $mongo = new \MongoClient();
    $cursor = $mongo->selectDB('testDB')->selectCollection('testCollection')->find();
    //[0=>['_id'=>MongoId(...), 'value'=>123], ...]
    
    
    $collection = new Collection($cursor);
    $collection->addModifier(function(&$item){
        $item['id'] = (string)$item['_id'];
    });
    $collection->addModifier(function(&$item){
        unset($item['_id']);
    });


        foreach($collection->getFilterIterator() as $item)
        {
            // $item = ['id'=>'4af9f23d8ead0e1d32000000', 'value'=>123]
        }
    

        $array = $collection->toArray();
        //$item = [ 0=> ['id'=>'4af9f23d8ead0e1d32000000', 'value'=>123], ...]
        foreach($array as $item)
        {
            //do stuff
        }
    

    $mongo = new \MongoClient();
    $cursor = $mongo->selectDB('testDB')->selectCollection('testCollection')->find();
    
    $it = new CallbackFilterIterator($cursor, function(&$item){
        $item['id'] = (string)$item['_id'];
        return true;
    });
    $it = new CallbackFilterIterator($it, function(&$item){
        unset($item['_id']);
        return true;
    });
    
    foreach($array as $item)
    {
        // $item = ['id'=>'4af9f23d8ead0e1d32000000', 'value'=>123]
    }

    $element = 'string';
    $collection->push($element);
    //or
    $collection[] = $element;

    $element2 = new stdClass();
    $collection->set(0, $element2);
    //or
    $collection[0] = $element2;
    // This throws Exception (offset 100 not exists)
    $collection->set(100, $element2);

    $collection->exists(0); 
    //or
    isset($collection[0]);

    $element = $collection->get(0); 
    //or
    $element = $collection[0];

    $element = $collection->remove(0);
    //or
    $element = unset($collection[0]);