How to dynamically set array keys in php

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

    You can use this if you want to get&set array values dynamically.

    function getVal($data,$chain){
        $level = $data;
        for($i=0;$i

    How it works:

    Calling getVal($data,array('foo','bar','2017-08')) will return the equivalent of $data['foo']['bar']['2017-08'].

    Calling setVal($data,array('foo','bar','2017-08'),'hello') will set value as if you called $data['foo']['bar']['2017-08'] = 'hello'. non-existent keys will be created automatically by php magic.

    This can be useful if you want to build the structure of the array dynamically.

提交回复
热议问题