gpt4 book ai didi

php - 如果值与 PHP 中数组中的其他值相关,如何从数组中删除数组?

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

我有一个数组,想从数组中删除相关值。

例。

In array [0] have 1/2/3 and [1] have 1/2/3/4 then [0] is a related to [1] so remove [0] which have 1/2/3 from the array.

另一个例子是

例。

[2] have 1/2/5, [3] have 1/2/5/6 and [4] have 1/2/5/6/7 then [2] and [3] depends on [4] so remove [2] and [3] both array form array.

有关详细信息,请查看以下示例。

Array
(
[0] => Array
(
[id] => 1/2/3
)

[1] => Array
(
[id] => 1/2/3/4
)

[2] => Array
(
[id] => 1/2/5
)

[3] => Array
(
[id] => 1/2/5/6
)

[4] => Array
(
[id] => 1/2/5/6/7
)
)

想要输出:

Array
(

[0] => Array
(
[id] => 1/2/3/4
)


[1] => Array
(
[id] => 1/2/5/6/7
)
)

我不知道我该怎么做。可能吗?

最佳答案

假设数组是有序的,您可以array_reverse 数组。使用 array_reduce 遍历数组,使用 strpos 检查字符串中子字符串第一次出现的位置。

$arr = //your array
$result = array_reduce( array_reverse( $arr ), function( $c, $v ){
if ( count( $c ) === 0 ) $c[] = $v;
else if ( count( $c ) && strpos( $c[0]['id'] , $v['id'] ) === false ) array_unshift( $c, $v );
return $c;
}, array());

echo "<pre>";
print_r( $result );
echo "</pre>";

这将导致:

Array
(
[0] => Array
(
[id] => 1/2/3/4
)

[1] => Array
(
[id] => 1/2/5/6/7
)

)

关于php - 如果值与 PHP 中数组中的其他值相关,如何从数组中删除数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51211254/

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