PHP中多维数组转一维数组 键值KEY不变【常用案例】

function multiArrToOneArrWithKeepKeys($params = array())
{
    if (empty($params) === TRUE)
        return array('msg' => 'nothing with array');
    $keys = array();
    $vals = array();
    $params = $this->multiArrToTwoArr($params);
    foreach ($params as $key => $val) {
        foreach ($val as $k => $v) {
            $keys[] = $k;
            $vals[] = $v;
        }
    }
    return array_combine($keys, $vals);
}

function multiArrToTwoArr($params = array())
{
    static $array;

    if (is_array($params)) {
        foreach ($params as $k => $p) {
            if (is_array($p))
                $this->multiArrToTwoArr($p);
            else
                $array[] = array($k => $p);
        }
    }
    return $array;
}


   $a = ['name' => 'Joe', 'languages' => ['PHP', 'Ruby']];
    print_r($this->multiArrToOneArrWithKeepKeys($a));
最后修改:2019 年 12 月 25 日 08 : 47 PM
如果觉得我的文章对你有用,请随意赞赏

发表评论