How to dynamically set array keys in php

前端 未结 6 2398
星月不相逢
星月不相逢 2021-02-20 18:48

I have some logic that is being used to sort data but depending on the user input the data is grouped differently. Right now I have five different functions that contain the sa

6条回答
  •  有刺的猬
    2021-02-20 19:49

    I agree with the comment on the OP by @Jake N that perhaps using objects is a better approach. Nonetheless, if you want to use arrays, you can check for the existence of keys in a conditional, like so:

    if(
        array_key_exists('Resource', $meter)
    ) {
        $calcs[$meter['Resource']['name']][$meter['UnitType']['name']][date('Y-m',$start)] = $data;
    } else {
        $calcs[$meter['UnitType']['name']] = $data;
    }
    

    On the other hand, if you want to use objects, you can create a MeterReading object type, and then add MeterReading instances as array elements to your $calcs array, like so:

    // Object defintion
    class MeterReading {
        private $data;
        private $resource;
        private $startDate;
        private $unitType;
    
        public function __construct(Array $meter, $start, $data) {
            $this->unitType   = $meter['UnitType']['name'];
            $this->resource   = $meter['Resource']['name'];
            $this->startDate  = date('Y-m',$start);
        }
    
        public function data() {
            return $this->data;
        }
    
        public function resource() {
            return $this->resource;
        }
    
        public function startDate() {
            return $this->startDate;
        }
    
        public function unitType() {
            return $this->unitType;
        }
    }
    
    // Example population
    $calcs[] = new MeterReading($meter, $start, $data);
    
    // Example usage
    foreach($calcs as $calc) {
        if($calc->resource()) {
            echo 'Resource: ' . $calc->resource() . '
    '; } echo 'Unit Type: ' . $calc->unitType() . '
    '; echo 'Start Date: ' . $calc->startDate() . '
    '; echo 'Data: ' . $calc->data() . '
    '; }

    Obviously you can take this further, such as checking the existence of array keys in the object constructor, giving the object property resource a default value if not provided, and so on, but this is a start to an OO approach.

提交回复
热议问题