Add 2 values to 1 key in a PHP array

后端 未结 7 1132
面向向阳花
面向向阳花 2021-02-08 03:35

I have a result set of data that I want to write to an array in php. Here is my sample data:

**Name** **Abbrev**
Mike     M
Tom      T
Jim      J
7条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-08 04:09

    maybe you create a simple class for that as the abbreviation is redundant information in your case

    class Person
    {
        public $name;
    
        pulbic function __construct($name)
        {
            $this->name = (string)$name;
        }
    
        public function getAbbrev()
        {
            return substr($this->name, 0, 1);
        }
    
        public function __get($prop)
        {
            if ($prop == 'abbrev') {
    
                return $this->getAbbrev();
            }
        }
    }
    
    
    $persons = array(
        new Person('Mike'),
        new Person('Tom'),
        new Person('Jim')
    );
    
    foreach ($persons as $person) {
    
       echo "$person->name ($person->abbrev.)
    "; }

提交回复
热议问题