How to “flatten” a multi-dimensional array to simple one in PHP?

前端 未结 23 2128
没有蜡笔的小新
没有蜡笔的小新 2020-11-22 01:03

It\'s probably beginner question but I\'m going through documentation for longer time already and I can\'t find any solution. I thought I could use implode for each dimensio

23条回答
  •  遇见更好的自我
    2020-11-22 01:14

    If you're interested in just the values for one particular key, you might find this approach useful:

    function valuelist($array, $array_column) {
        $return = array();
        foreach($array AS $row){
            $return[]=$row[$array_column];
        };
        return $return;
    };
    

    Example:

    Given $get_role_action=

    array(3) {
      [0]=>
      array(2) {
        ["ACTION_CD"]=>
        string(12) "ADD_DOCUMENT"
        ["ACTION_REASON"]=>
        NULL
      }
      [1]=>
      array(2) {
        ["ACTION_CD"]=>
        string(13) "LINK_DOCUMENT"
        ["ACTION_REASON"]=>
        NULL
      }
      [2]=>
      array(2) {
        ["ACTION_CD"]=>
        string(15) "UNLINK_DOCUMENT"
        ["ACTION_REASON"]=>
        NULL
      }
    }
    

    than $variables['role_action_list']=valuelist($get_role_action, 'ACTION_CD'); would result in:

    $variables["role_action_list"]=>
      array(3) {
        [0]=>
        string(12) "ADD_DOCUMENT"
        [1]=>
        string(13) "LINK_DOCUMENT"
        [2]=>
        string(15) "UNLINK_DOCUMENT"
      }
    

    From there you can perform value look-ups like so:

    if( in_array('ADD_DOCUMENT', $variables['role_action_list']) ){
        //do something
    };
    

提交回复
热议问题