gpt4 book ai didi

PHP array_merge_recursive 与一个数组

转载 作者:搜寻专家 更新时间:2023-10-31 21:01:34 25 4
gpt4 key购买 nike

我正在为 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 函数。 IE。 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 键的值将始终是一个数组。在我看来,这使得以后处理数据更容易,因为您不必担心检查字符串还是数组。

关于PHP array_merge_recursive 与一个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41167765/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com