2

i need help about how to remove one or more array child from set of array that have exactly same keys and values with other child in PHP. Please take a look this array:

Array
(
    [0] => Array
        (
            [scn_fr_tm] => 10:35
            [scn_to_tm] => 12:55
            [mov_prnt_nm] => Thor Ragnarok
        )
    [1] => Array
        (
            [scn_fr_tm] => 10:40
            [scn_to_tm] => 12:39
            [mov_prnt_nm] => Geostorm
        )
    [2] => Array
        (
            [scn_fr_tm] => 11:30
            [scn_to_tm] => 13:22
            [mov_prnt_nm] => One Fine Day
        )
    [3] => Array
        (
            [scn_fr_tm] => 11:30
            [scn_to_tm] => 13:22
            [mov_prnt_nm] => One Fine Day
        )
    [4] => Array
        (
            [scn_fr_tm] => 11:30
            [scn_to_tm] => 13:00
            [mov_prnt_nm] => Total Chaos
        )
    [5] => Array
        (
            [scn_fr_tm] => 11:30
            [scn_to_tm] => 13:22
            [mov_prnt_nm] => One Fine Day
        )
)

as you can see from above array, i want to remove array[3] and array[5] from array because it has duplicate keys and values with array[2]. Above array created dynamically, so please don't ask me to use unset(array[3]) and unset(array[5]).

here is my array creation code, the array created from other array:

foreach ($datas as $data)
{
    if (array_key_exists('attr', $data))
    {
        $arr[] = array(
            'scn_fr_tm'     => substr_replace($data['attr'][0]['scn_fr_tm'],':',2,0),
            'scn_to_tm'     => substr_replace($data['attr'][0]['scn_to_tm'],':',2,0),
            'mov_prnt_nm'   => substr($data['mov_prnt_nm'], 0, 20)
        );
    }
}

Thank you for your help

3
  • could be done in the array creation code, but you dont show that so .. Commented Nov 2, 2017 at 20:42
  • Thanks @nogad, i had edit my question Commented Nov 2, 2017 at 20:47
  • 1
    i would create an array to just hold titles as you build the new array, then you can use a simple in_array() check before adding to your main array Commented Nov 2, 2017 at 20:49

1 Answer 1

1

I thought of a couple of different options:

$unique = array_map('unserialize', array_unique(array_map('serialize', $array)));

or

while ($item = array_pop($array)) {
    if (!in_array($item, $array)) {
        $unique[] = $item;
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

You're welcome. You know, as far as the in_array one, you can do as @nogad suggested in the comments and just check for that before adding each item into the array as you build it. That should be a bit more efficient that trying to make it unique afterward.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.