arrays - PHP data collection - use class construct to replace numerical key with string ident -


i experimenting data collection objects , want use class construct make changes array keys of arrays passed newly instantiated object.

the main idea arrays can passed numerical keys , each numerical key replaced string value. system predicated on fact arrays single array of array each containing 3 key/value pairs. (see data example). know fragile , intend address issue next.

class:

class newscollection {      private $collection;      public function __construct($data)     {         foreach ($data[0] $key => $value) {              switch ($key) {                 case 0:                     // replace key id string ie. 0 "headline"                     break;                 case 1:                     // replace key id string ie. 1 "date"                     break;                 case 2:                     // replace key id string ie. 2 "author"                     break;             }         }          $this->collection = $data;     }      public function getnewscollection()     {         return $this->collection;     } } 

data (array):

$sports = [     [         "boston red sox vs new york yankees - 9-3",         "19.06.2017",         "espn"     ],     [        "boston patriot qb breaks new record!",        "16.07.2017",        "nesn"     ],     [         "celtics coach john doe inducted hall of fame",         "25.07.2017",         "fox sports"     ],     [         "boston brewins win 16-5 against new york's rangers",         "21.08.2017",         "nesn"     ] ]; 

example of desire result:

$sports = [     [         "headline" => boston red sox vs new york yankees - 9-3",         "date => "19.06.2017",         "author" => "espn"     ],     ect.. ];  

you can make array desired keys, , use array_combine() set them keys of input array. this:

private $keys = [     "headline",     "date",     "author", ];  // ...  public function __construct($data) {     foreach ($data &$el) {         $el = array_combine($this->keys, $el);     }      $this->collection = $data; } 

notice it's done reference, we're modifying actual element inside foreach loop. should verification according needs.

as side note, should not work in constructor. it'll bring problems down road. it's better have function initial work input values:

<?php class newscollection {      private $collection;     private $keys = [         "headline",         "date",         "author",     ];      public function __construct($data)     {         $this->collection = $data;     }      public function assingkeys() {         foreach ($this->collection &$el) {             $el = array_combine($this->keys, $el);         }     }      public function getnewscollection()     {         return $this->collection;     } }  $c = new newscollection($sports); $c->assignkeys(); $collection = $c->getnewscollection(); 

demo


Comments