Last active
April 28, 2019 06:36
-
-
Save shiny/01f915a33e940e9f72b0616876a3c5d2 to your computer and use it in GitHub Desktop.
多维数组.php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$a = [ 'Date','Media','Geo' ]; | |
$b = [ 'Num' ]; | |
$subject = [ 'Date'=>'2019-04-26','Media'=>'AAA','Geo'=>'CN','Num'=>105 ]; | |
// 多维数组的最后一项 | |
$value = array_intersect_key($subject, array_fill_keys($b, 1)); | |
// 生成多维数组 | |
$res = createMultiArray($a, $value, $subject); | |
var_dump([ | |
'res' => $res | |
]); | |
/** | |
* createMultiArray 根据数据创建多维数组 | |
* @param array $multiKeys 根据提供的 $multiKeys,查找 source,取值为 key 创建多维数组 | |
* @param mixed $value 最后一个数组的值 | |
* @param array $source 数据源 | |
* @return array 创建的多维数组 | |
*/ | |
function createMultiArray($multiKeys, $value, $source) { | |
$structure = []; | |
$pointer = &$structure; | |
foreach($multiKeys as $multiKey) { | |
$key = $source[$multiKey]; | |
// 这里引用了下一级数组 | |
$pointer = &$pointer[$key]; | |
} | |
$pointer = $value; | |
return $structure; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
我针对自己的实际业务代码应用了下你的功能,再次再次非常感谢了,我自己加了个unset,因为我发现最后的数组中,会有一个引用数组,不知道会不会有什么影响