PHP code example of eftec / arrayone

1. Go to this page and download the library: Download eftec/arrayone 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/ */

    

eftec / arrayone example snippets


// Reducing an array using aggregate functions:
$invoice=[
    'id'=>1,
    'date'=>new DateTime('now'),
    'customer'=>10,
    'detail'=>[
        ['idproduct'=>1,'unitPrice'=>200,'quantity'=>3],
        ['idproduct'=>2,'unitPrice'=>300,'quantity'=>4],
        ['idproduct'=>3,'unitPrice'=>300,'quantity'=>5],
    ]
];
$arr=ArrayOne::set($invoice['detail'])
    ->reduce(['unitPrice'=>'sum','quantity'=>'sum'])
    ->all(); //['unitPrice'=>800,'quanty'=>12]
// or also
$arr=(new ArrayOne($invoice['detail']))
    ->reduce(['unitPrice'=>'sum','quantity'=>'sum'])
    ->all(); //['unitPrice'=>800,'quanty'=>12]

use eftec\ArrayOne;
ArrayOne::set($array); // Initial operator: $array is our initial array.
    ->someoperator1()  // Middle operator: here we do one or many operations to transform the array
    ->someoperator2()
    ->someoperator3()
    ->all(); // End operator: and we get the end result that usually is an array but it could be even a literal.

$array=['hello'  // indexed field
       'field2'=>'world', // named field
       'fields'=>[   // a field with sub-fields
           'alpha'=>1,
           'beta'=>2
       ],
       'table'=>[ // a field with a list of values (a table)
           ['id'=>1,'name'=>'red'],
           ['id'=>2,'name'=>'orange'],
           ['id'=>3,'name'=>'blue'],           
       ]
   ];

ArrayOne::set($array)->all();
ArrayOne::set($array,$object)->all(); // the object is used by validation()
ArrayOne::set($array,SomeClass:class)->all(); // the object is used by validation()

ArrayOne::setRequest([
    'id'=>'get', // $_GET['id'] if not found then it uses the default value (null)
    'name'=>'post|default', // $_POST['name'], if not found then it uses "default"
    'content'=>'body' // it reads from the POST body
],null); // null is the default value if not other default value is set.

ArrayOne::setJson('{"a":3,"b":[1,2,3]}')->all();

ArrayOne::setCsv("a,b,c\n1,2,3\n4,5,6")->all();

ArrayOne::setCsvHeadLess("1,2,3\n4,5,6")->all(); 
ArrayOne::setCsvHeadLess("1,2,3\n4,5,6",['c1','c2','c3'])->all();

ArrayOne::set($array)
    ->group('col1',['col2'=>'sum']) // middle operator #2
    ->all();

$this->col('c1'); // [['c1'=>1,'c2'=>2],['c1'=>3,'c2'=>4]] => [['c1'=>1],['c1'=>3]];

$this->indexToField('colold'); //  [['colold'=>'a','col1'=>'b','col2'=>'c'] => ['a'=>['col1'=>'b','col2'=>'c']]

$array = [['id' => 1, 'name' => 'chile'], ['id' => 2, 'name' => 'argentina'], ['id' => 3, 'name' => 'peru']];
// get the row #2 "argentina":
// using a function:
$r = ArrayOne::set($array)->filter(function($row, $id) {return $row['id'] === 2;}, true)->result();
// using a function a returning a flat result:
$r = ArrayOne::set($array)->filter(function($row, $id) {return $row['id'] === 2;}, false)->result();
// using an associative array:
$r = ArrayOne::set($array)->filter(['id'=>'eq;2'], false)->result();
// using an associative array that contains an array:
$r = ArrayOne::set($array)->filter(['id'=>['eq,2]], false)->result();
// multiples conditions: id=2 and col=10
$r = ArrayOne::set($array)->filter([['id'=>'eq;2'],['col','eq;10]], false)->result();

ArrayOne::set($array)->find(function($row, $id) {
          return $row['id'] === 2;
          })->all(); // [[0,"apple"],[3,"pear"]]

ArrayOne::isIndexArray(['cocacola','fanta']); // true
ArrayOne::isIndexArray(['prod1'=>'cocacola','prod2'=>'fanta']); // false (associative array)
ArrayOne::isIndexArray('cocacola'); // false (not array)
ArrayOne::set(['cocacola','fanta'])->isIndex(); // dynamic method (true)

ArrayOne::isIndexTableArray([['cocacola','fanta']]); // true
ArrayOne::isIndexTableArray(['cocacola','fanta']); // false
ArrayOne::isIndexTableArray(['first'=>['hello'],'second'=>'world']) // false

$this->flat(); // [['a'=>1,'b'=>2]] => ['a'=>1,'b'=>2]

// group in the same column using a predefined function:
$this->group('type',['c1'=>'sum','price'=>'sum']); // ['type1'=>['c1'=>20,'price'=>30]]
// group in a different column using a predefined function:
$this->group('type',['newcol'=>'sum(amount)','price'=>'sum(price)']);
// group using an indexed index:
$this->group('type',['c1'=>'sum','pri'=>'sum','grp'=>'group'],false); // [['c1'=>20,'pri'=>30,'grp'=>'type1']]
// group using a function:
$this->group('type',['c1'=>function($cumulate,$row) { return $cumulate+$row['c1'];}]);
// group using two functions, one per every row and the other at the end:
$this->group('type',['c1'=>[
		  function($cumulate,$row) { return $cumulate+$row['c1'];},
		  function($cumulate,$numrows) { return $cumulate/$numRows;}]); // obtain the average of c1

$array=[
    ['cat'=>'cat1','col_min'=>1,'col_max'=>1,'col_sum'=>1,'col_avg'=>1,'col_first'=>'john1','col_last'=>'doe1'],
    ['cat'=>'cat2','col_min'=>2,'col_max'=>2,'col_sum'=>2,'col_avg'=>2,'col_first'=>'john2','col_last'=>'doe2'],
    ['cat'=>'cat3','col_min'=>3,'col_max'=>3,'col_sum'=>3,'col_avg'=>3,'col_first'=>'john3','col_last'=>'doe3'],
    ['cat'=>'cat1','col_min'=>4,'col_max'=>4,'col_sum'=>4,'col_avg'=>4,'col_first'=>'john4','col_last'=>'doe4'],
    ['cat'=>'cat2','col_min'=>5,'col_max'=>5,'col_sum'=>5,'col_avg'=>5,'col_first'=>'john5','col_last'=>'doe5']
    ];
$result=ArrayOne::set($array)
    ->group('cat',[
        'col_min'=>'min',
        'col_max'=>'max',
        'col_sum'=>'sum',
        'col_avg'=>'avg',
        'col_count'=>'count',
        'col_first'=>'first',
        'col_last'=>'last',
    ])
    ->all();
/* [
    'cat1' =>
        ['col_min' => 1, 'col_max' => 4, 'col_sum' => 5, 'col_avg' => 2.5, 'col_first' => 'john1', 'col_last' => 'doe4', 'col_count' => 2,],
    'cat2' =>
        ['col_min' => 2, 'col_max' => 5, 'col_sum' => 7, 'col_avg' => 3.5, 'col_first' => 'john2', 'col_last' => 'doe5', 'col_count' => 2,],
    'cat3' =>
        ['col_min' => 3, 'col_max' => 3, 'col_sum' => 3, 'col_avg' => 3, 'col_first' => 'john3', 'col_last' => 'doe3', 'col_count' => 1,],
];


$this->indexToCol('colnew'); // ['a'=>['col1'=>'b','col2'=>'c']] => [['colnew'=>'a','col1'=>'b','col2'=>'c']

$products=[['id'=>1,'name'=>'cocacola','idtype'=>123]];
$types=[['id'=>123,'desc'=>'it is the type #123']];
ArrayOne::set($products)->join($types,'idtype','id')->all()
// [['id'=>1,'prod'=>'cocacola','idtype'=>123,'desc'=>'it is the type #123']] "id" is from product.

$this->map(function($row) { return strtoupper($row); });

$array=['a'=>1,'b'=>2,'c'=>3,'items'=>[[a1'=>1,'a2'=>2,'a3'=3],[a1'=>1,'a2'=>2,'a3'=3]];
$mask=['a'=>1,'items'=>[[a1'=>1]]; // [[a1'=>1]] masks an entire table
$this->mask($mask); // $array=['a'=>1,'items'=>[[a1'=>1],[a1'=>1]];

$this->reduce(['col1'=>'sum','col2'=>'avg','col3'=>'min','col4'=>'max']);
$this->reduce(function($row,$index,$prev) { return ['col1'=>$row['col1']+$prev['col1]];  });

$this->removeCol('col1');
$this->removeCol(['col1','col2']);

$this->removeRow(20);

$this->removeFirstRow(); // remove the first row
$this->removeFirstRow(3); // remove the first 3 rows

$this->removeLastRow(); // remove the last row
$this->removeLastRow(3); // remove the last 3 rows

$this->removeDuplicate('col');

$this->modCol('col1',function($row,$index) { return $row['col2']*$row['col3'];  });

$this->sort('payment','desc'); // sort an array using the column paypent descending.
$this->sort(['col1','col2'],'desc');
$this->sort(['col1','col2'],['desc','asc']);

$valid=$this->set($array)->validate([
         'id'=>'int',
    	 'price'=>'int|between;1,20'   // the price must be an integer and it must be between 1 and 20 (including them).
         'table'=>[['col1'=>'int';'col2'=>'string|notnull,,the value is s. If nested array, then some values could be overriden.
$valid->isValid(); // returns true if the validation passes, otherwise, it returns false.

// 1) defining the service class.
class ServiceClass {
	/**
     * @param mixed $value the value to evaluate 
     * @param mixed $compare the value to compare (optional)
     * @param ?string $msg the message to return if fails
     * @return bool
     */
    public function test($value,$compare=null,&$msg=null): bool
    {
        return true;
    }
}
// 2.1) and setting the service class using the class
ValidateOne
    ->set($array,ServiceClass:class)
    ->validate('field'=>'fn:test') // or ->validate('field'=>[['fn','test']])
    ->all();
// 2.2) or you could use an instance
$obj=new ServiceClass();
ValidateOne
    ->set($array,$obj)
    ->validate('field'=>'fn:test') // or ->validate('field'=>[['fn','test']])
    ->all();

$this->set($array)->getAll();

if ($this->set($array)->valid($arrayComparison)->isValid()) {
  // do something.
}

$this->set($array)->all();

$this->makeValidateArrayByExample(['1','a','f'=>3.3]); // ['int','string','f'=>'float'];

$this->makeRequestArrayByExample(['a'=1,'b'=>2]); // ['a'='post','b'=>'post'];

// before:
$r=ArrayOne::set($array)->nav('field')->...->all();
// now:
$r=ArrayOne::set($array['field'])->...->all();
// before:
$r=ArrayOne::set($array)->nav('field')->...->currentArray();
// now:
$r=$array;
$r['field']=ArrayOne::set($array['field'])->...->all();