Connor McManus Connor McManus - 3 months ago 13
PHP Question

PHP Search Multidimensional Array for Duplicate Values

I have an array like this:

[0] => Array
(
[0] => Array
(
[Foo] => Bar
[Foo2] => String1
)

)

[1] => Array
(
[0] => Array
(
[Foo] => Bar
[Foo2] => String2
)

)


While the one I'm working with is a lot larger, that's the general form of it. I'm trying to look at each value relative to Foo, and if there is a repeat in one of the arrays, take the subsequent Foo2 value and "push" it to a new array, essentially looking like this:

[0] => Array
(
[0] => Array
(
[Foo] => Bar
[Foo2] => String1,
String2
)

)


Basically I just want to know if this is even possible!!

Answer

The solution using isset and array_values functions:

$grouped = [];
foreach ($arr as $v) {  // $arr is your initial array
    $foo = $v[0]['Foo'];
    if (!isset($grouped[$foo])) {
        $grouped[$foo] = $v[0];
    } else {
        $grouped[$foo]['Foo2'] .= "," . $v[0]['Foo2'];
    }
}
$result = array_values($grouped);
print_r($result);

DEMO link