How to dynamically set array keys in php

前端 未结 6 2467
星月不相逢
星月不相逢 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:47

    Would it not be easier to do the following

    $calcs = array(
        $meter['Resource']['name'] => array(
            $meter['UnitType']['name'] => 'Some Value',
            $meter['UnitType']['name2'] => 'Some Value Again'
        ),
    );
    

    or you can use Objects

    $calcs = new stdClass();
    $calcs->{$meter['UnitType']['name']} = 'Some Value';
    

    but I would advice you build your structure in arrays and then do!

    $calcs = (object)$calcs_array;
    

    or you can loop your first array into a new array!

    $new = array();
    $d = date('Y-m',$start);
    foreach($meter as $key => $value)
    {
        $new[$key]['name'][$d] = array();
    }
    

    Give it ago and see how the array structure comes out.

提交回复
热议问题