I have an array and want to remove the related value form array.
Ex.
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.
Another Example is
Ex.
[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.
For more details please check below example.
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
)
)
Want Output :
Array
(
[0] => Array
(
[id] => 1/2/3/4
)
[1] => Array
(
[id] => 1/2/5/6/7
)
)
I don't have an idea how can I do that. Is it possible?
Assuming that the array is in order, you can array_reverse the array. Use array_reduce to loop thru the array, Use strpos to check position of the first occurrence of a substring in a string.
$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>";
This will result to:
Array
(
[0] => Array
(
[id] => 1/2/3/4
)
[1] => Array
(
[id] => 1/2/5/6/7
)
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With