1

I have to array, in text field might get duplicated data, I want to combine two array into one with unique text

$a = array(
    array(
        'domain' => 'default',
        'text' => 'a',
    ),
    array(
        'domain' => 'default',
        'text' => 'b',
    ),
);
$b = array(
    array(
        'domain' => 'default',
        'text' => 'a',
    ),
    array(
        'domain' => 'default',
        'text' => 'c',
    ),
);

expected result

array(
    array(
        'domain' => 'default',
        'text' => 'a',
    ),
    array(
        'domain' => 'default',
        'text' => 'c',
    ),
    array(
        'domain' => 'default',
        'text' => 'b',
    ),
);

This is how I do it now

$merged = array_merge($a, $b);
$extractText = array_map(function($item) {
    return $item['text'];
}, $merged);
$result = array_map(function($item) {
    return array(
        'domain' => 'default',
        'text' => $item
    );
}, array_unique($extractText));
var_dump($result);

Looking for origin PHP way or another way more efficient to achieve this.

3
  • Please put your desired result. Not sure what "unique text" means. Commented Feb 15, 2019 at 6:57
  • @mitkosoft it's done, thanks Commented Feb 15, 2019 at 6:59
  • Seems like you want a array with unique sub arrays, right? Commented Feb 15, 2019 at 7:03

2 Answers 2

4

This should work -

$merged =array_merge($a, $b);
array_unique($merged, SORT_REGULAR);

Output

array:3 [▼
  0 => array:2 [▼
    "domain" => "default"
    "text" => "a"
  ]
  1 => array:2 [▼
    "domain" => "default"
    "text" => "b"
  ]
  3 => array:2 [▼
    "domain" => "default"
    "text" => "c"
  ]
]

array_unique()

SORT_REGULAR - compare items normally (don't change types)

Sign up to request clarification or add additional context in comments.

Comments

1

You can use array_unique for this job, the trick is that you have to specify SORT_REGULAR as the second parameter. This prevents array_unique from trying to cast the array values as strings:

$result = array_unique(array_merge($a, $b), SORT_REGULAR);
print_r($result);

Output:

Array (
    [0] => Array (
        [domain] => default
        [text] => a
    )
    [1] => Array (
        [domain] => default
        [text] => b
    )
    [3] => Array (
        [domain] => default
        [text] => c
    )
)

Demo on 3v4l.org

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.