Upgrade to Pro — share decks privately, control downloads, hide ads and more …

PHP Map

Aimeos
September 04, 2020

PHP Map

Easy to use and elegant handling for PHP arrays using Map objects

Aimeos

September 04, 2020

Transcript

28 slides
  1. $list = [ ['id' => '1', 'value' => 'value1'], ['id'

    => '2', 'value' => 'value2'], null ]; Starting point
  2. $list[] = ['id' => '3', 'value' => 'value3']; unset($list[0]); $list

    = array_filter($list); sort($list); $pairs = array_column($list, 'value', 'id'); $value = reset($pairs) ?: null; Current way
  3. $value = map( $list ) ->push(['id' => '3', 'value' =>

    'value3']) ->remove(0) ->filter() ->sort() ->col('value', 'id') ->first(); Using Map
  4. $map[] = ['id' => '3', 'value' => 'value3']; $value =

    $map[0]; count($map); foreach($map as $key => value) {} Still possible
  5.  map()  new Map()  Map::from() Creating maps 

    map([1, 2, 3])  map(new Map())  map($iterator)  map('abc')
  6.  concat()  collapse()  duplicates()  flat()  countBy()

     groupBy() Additional methods  except()  only()  pull()  take()  skip()  ...
  7.  concat()  every()  find()  flat()  includes()

     join()  keys() Like Javascript  map()  pop()  push()  reduce()  reverse()  some()  ...
  8. Map::method( 'strrev', function($sep) { return strrev(join($sep, $this->list)); } ); Map::from(['c',

    'b', 'a'])->strrev(' > '); // returns 'a > b > c' Custom methods
  9. class MyClass { private $code; private $status = 0; public

    function __construct( $code ) { $this->code = $code; } public function setStatus( int $s ) { $this->stat = $s; return $this; } public function getCode() { return $this->code; } } Example class
  10. $objects = Map::from( [ 'a' => new MyClass( 'x' ),

    'b' => new MyClass( 'y' ) ] ); Example Map
  11. // status of all object is 1 // $result contains:

    ['a' => 'x', 'b' => 'y'] Result
  12. ?

More Decks by Aimeos

Other Decks in Programming