简体   繁体   English

带有一个数组的PHP array_merge_recursive

[英]PHP array_merge_recursive with one array

I am struggling with a data structure in PHP. 我正在努力使用PHP中的数据结构。 I'm trying to use array_merge_recursive to condense an array by like keys and then grab all values instead of having them overwritten. 我正在尝试使用array_merge_recursive通过类似的键压缩数组,然后获取所有值而不是覆盖它们。 This is why I chose array_merge_recursive instead of array_merge . 这就是我选择array_merge_recursive而不是array_merge

My array is something similar to: 我的数组类似于:

Array
(
  [0] => Array
  (
    [App] => APP1
    [Type] => DB
  )
  [1] => Array
  (
    [App] => APP1
    [Type] => WEBSITE
  )
  [2] => Array
  (
    [App] => APP2
    [Type] => IOS
  )
)

I was expecting array_merge_recursive to combine like keys and then group the other elements into arrays however this is not the behavior I am seeing. 我期待array_merge_recursive组合像键,然后将其他元素分组到数组中,但这不是我看到的行为。

I am hoping to get an array like the following: 我希望得到如下数组:

Array
(
  [0] => Array
  (
    [App] => APP1
    [Type] => Array
    (
      [0] => DB
      [1] => WEBSITE
    )
  )
  [1] => Array
  (
    [App] => APP2
    [Type] => IOS
  )
)

array_merge_recursive() does not do what you think it does. array_merge_recursive()不会按照您的想法执行。 You are looking for a function that restructures an array based on specific rules that are helpful to you and as such there isn't a builtin php function for that. 您正在寻找一个函数,该函数根据对您有帮助的特定规则重构数组,因此没有内置的php函数。 Ie How would PHP know that you wanted to new array to be structured by APP rather TYPE . 即PHP如何知道您希望新的数组由APP而不是TYPE构建。 Assuming your array is always that simple, the easiest version of the function you want looks something like this: 假设您的数组总是那么简单,那么您想要的最简单的函数版本如下所示:

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

}

Note, in this solution, the value of the TYPE key in every APP will always be an array. 注意,在此解决方案中,每个APP TYPE键的值将始终为数组。 This makes handling the data later easier in my opinion since you don't have to worry about checking for a string vs an array. 这使我以后更容易处理数据,因为您不必担心检查字符串与数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM