PHP转换嵌套数组到单一阵列中,同时串联钥匙? [英] PHP convert nested array to single array while concatenating keys?

查看:133
本文介绍了PHP转换嵌套数组到单一阵列中,同时串联钥匙?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是一个例子数组:

 $foo = array(
           'employer' => array(
                    'name' => 'Foobar Inc',
                    'phone' => '555-555-5555'
                     ),
           'employee' => array(
                    'name' => 'John Doe',
                    'phone' => '555-555-5556',
                    'address' => array(
                           'state' => 'California',
                           'zip' => '90210'
                        )
                    ),
           'modified' => '2009-12-01',
         );

和我想获得这样的结果是:

And I would like to get a result like this:

$fooCompressed = array(
             'employer_name' => 'Foobar Inc',
             'employer_phone' => '555-555-5555',
             'employee_name' => 'John Doe',
             'employee_phone' => '555-555-5556'
             'employee_address_state' => 'California',
             'employee_address_zip' => '90210',
             'modified' => '2009-12-01'
             )

我将如何去写一个递归函数来处理呢?

How would I go about writing a recursive function to handle this?

推荐答案

事情是这样的:

function makeNonNestedRecursive(array &$out, $key, array $in){
    foreach($in as $k=>$v){
    	if(is_array($v)){
    	    makeNonNestedRecursive($out, $key . $k . '_', $v);
    	}else{
            $out[$key . $k] = $v;
    	}
    }
}

function makeNonNested(array $in){
    $out = array();
    makeNonNestedRecursive($out, '', $in);
    return $out;
}

// Example
$fooCompressed = makeNonNested($foo);

这篇关于PHP转换嵌套数组到单一阵列中,同时串联钥匙?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆