Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove array from array if value have related to other value in array in PHP?

Tags:

arrays

regex

php

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?

like image 985
R P Avatar asked Mar 15 '26 16:03

R P


1 Answers

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
        )

)
like image 187
Eddie Avatar answered Mar 17 '26 04:03

Eddie