gpt4 book ai didi

PHP - 过滤数组以从子数组中删除具有不相似键的值

转载 作者:行者123 更新时间:2023-12-05 05:14:59 24 4
gpt4 key购买 nike

我有一个如下所示的数组。这是来自一个集中式数据库,我无法事先知道实际数组将包含什么。我想比较键上的子数组,这就是为什么要删除不存在的键是所有子数组。

Array (
[0] => Array
(
[a] =>
[b] => 8
[c] => 1
[d] => taille-8
[e] =>
[k] => taill
)

[1] => Array
(
[a] =>
[b] => 7
[c] => 2
[d] => taille-7
[f] =>
[k] => tafefef
)

[2] => Array
(
[a] => ce
[b] => 34
[c] => 2
[d] => taille-34
[g] => dee
[k] => tacefef
) );

我想删除所有子数组中不重复的键。在上面的示例中,它们是“e”、“f”和“g”。这需要动态发生。

Array (
[0] => Array
(
[a] =>
[b] => 8
[c] => 1
[d] => taille-8
[k] => taill
)

[1] => Array
(
[a] =>
[b] => 7
[c] => 2
[d] => taille-7
[k] => tafefef
)

[2] => Array
(
[a] => ce
[b] => 34
[c] => 2
[d] => taille-34
[k] => tacefef
) );

任何建议表示赞赏。

最佳答案

您可以使用参数解包。如果您的数组存储在 $a 中,那么以下应该有效:

// create an array with only the keys that are common to all subarrays
$new = array_intersect_key(...$a);

// prune original array
foreach ($a as &$arr) {
$arr = array_intersect_key($new, $arr);
}

关于PHP - 过滤数组以从子数组中删除具有不相似键的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51998070/

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