[英]PHP array_merge_recursive with one array
我正在努力使用PHP中的数据结构。 我正在尝试使用array_merge_recursive
通过类似的键压缩数组,然后获取所有值而不是覆盖它们。 这就是我选择array_merge_recursive
而不是array_merge
。
我的数组类似于:
Array
(
[0] => Array
(
[App] => APP1
[Type] => DB
)
[1] => Array
(
[App] => APP1
[Type] => WEBSITE
)
[2] => Array
(
[App] => APP2
[Type] => IOS
)
)
我期待array_merge_recursive
组合像键,然后将其他元素分组到数组中,但这不是我看到的行为。
我希望得到如下数组:
Array
(
[0] => Array
(
[App] => APP1
[Type] => Array
(
[0] => DB
[1] => WEBSITE
)
)
[1] => Array
(
[App] => APP2
[Type] => IOS
)
)
array_merge_recursive()
不会按照您的想法执行。 您正在寻找一个函数,该函数根据对您有帮助的特定规则重构数组,因此没有内置的php函数。 即PHP如何知道您希望新的数组由APP
而不是TYPE
构建。 假设您的数组总是那么简单,那么您想要的最简单的函数版本如下所示:
function sortByApp($array){
$result = array();
foreach($array as $row){
if(!isset( $result[ $row['APP'] ] ) {
$result[ $row['APP'] ] = array(
'APP' => $row['APP'],
'TYPE' => array( $row['TYPE'] )
);
}else{
$result[ $row['APP'] ]['TYPE'] = array_merge( $result[ $row['APP'] ]['TYPE'], array($row['TYPE']) );
}
}
$result = array_values($result); //All this does is remove the keys from the top array, it isn't really necessary but will make the output more closely match what you posted.
return $result
}
注意,在此解决方案中,每个APP
TYPE
键的值将始终为数组。 这使我以后更容易处理数据,因为您不必担心检查字符串与数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.