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::isIndexArray(['cocacola','fanta']); // true
ArrayOne::isIndexArray(['prod1'=>'cocacola','prod2'=>'fanta']); // false (associative array)
ArrayOne::isIndexArray('cocacola'); // false (not array)

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

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

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

ArrayOne::makeWalk(['a'=>'hello','b'=>['c'=>'world'],function($row,$id) { return strotupper($row);});

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

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::setJson('{"a":3,"b":[1,2,3]}')->all();

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.

$sum=$this->set($arr)->aggr('sum','col'); // returns sum of the column 'col'
$min=$this->set($arr)->aggr('min','col'); // returns the min value of the column 'col'

$this->set($array)->nav('field')->all();

$max=$this->set($arr)->avg('col'); // returns the average of the column 'col'

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

$this->colRename('c1','n1'); // [['c1'=1,'c2'=>2]] => [['n1'=>1,'c2'=2]]
$this->colRename(['c1','c2'],['n1','n2']); // [['c1'=1,'c2'=>2]] => [['n1'=>1,'n2'=2]]

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

$max=$this->set($arr)->count(); // returns the count (number of elements)

$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();
$r = ArrayOne::set($array)->filter(fn($row, $id) => $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(); // 'eq;2' or simply '2'
// 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"]]

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

$this->set($array)->nav('field')->getAll();

// 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)']);
// multiples columns (columns are jointed using $this->separator)
$this->group(['col1,col2'],['col3'=>'sum']);
// 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

$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->keepCol('col1');
$this->keepCol(['col1','col2']);

$this->map(function($row) { return strtoupper($row); });
$this->map(function($row,$index) {$row['col1']=$row['col2']*$row['col3']; return $row });
$this->modCol('col1',function($row,$index) { return $row['col2']*$row['col3'];  }); // it does the same

$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]];

$max=$this->set($arr)->max('col'); // returns the max value of the column 'col'
$max=$this->set($arr)->max('col',true); // returns the key where is the max value

$max=$this->set($arr)->min('col'); // returns the min value of the column 'col'
$max=$this->set($arr)->min('col',true); // returns the key where is the min value

$this->modCol('col1',function($row,$index) { return $row['col2']*$row['col3'];  });
$this->map(function($row,$index) {$row['col1']=$row['col2']*$row['col3']; return $row }); // it does the same

$this->offsetGet(1); // $this->array[1];

$this->offsetSet(1,"hello"); // $this->array[1]="hello";

$this->offsetUnset(1); // unset($this->array[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']);

$dup=$this->removeDuplicate('col');
$dup=$this->removeDuplicate(['col1','col2']);

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

$this->removeLastRow(3);

$this->removeRow(20);

$values=[['a'=>1,'b'=>2'],['a'=>2,'b'=>3'],['c'=>4]];
$this->rowToValue('a'); // [1,2]
$this->rowToValue('a',true); // [1,2,null]

$this->sort('payment','desc'); // sort an array using the column paypent descending.
$this->sort(['payment','customer']); // sort both columns ascending.
$this->sort(); // it sorts the array ascending using the column
$this->sort(['payment','customer'],['asc','desc']); // sorth both columns, ascending and descending
$this->sort(['payment','customer'],'desc'); // it sorts both columns descending.

$max=$this->set($arr)->sum('col'); // returns the sum of the column 'col'

$this->set($arr)
->validate([
'id'=>'int',
'table'=>[['col1'=>'int','col2'=>'string']],   // note the double [[ ]] to indicate a table of values
'list'=>[['int']]
])
->all();
// example using custom function
// 1) defining the service class.
class ServiceClass {
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();

// 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();