0

I was wondering what is the best way to eliminate duplicates within an array? Currently I'm running through a foreach loop to actually get this array, is there a way to say, if id already exists, don't insert into array?

foreach($categories2Sugg as $Category2Sugg)
{

    $category_stringArray2Sugg[] = array("id"=>$Category2Sugg->id,"name"=>$Category2Sugg->name,"pluralName"=>$Category2Sugg->pluralName,"shortName"=>$Category2Sugg->shortName);      

}


Array
(
    [0] => Array
        (
            [id] => 4bf58dd8d48988d16c941735
            [name] => Burger Joint
            [pluralName] => Burger Joints
            [shortName] => Burgers
        )

    [1] => Array
        (
            [id] => 4bf58dd8d48988d16c941735
            [name] => Burger Joint
            [pluralName] => Burger Joints
            [shortName] => Burgers
        )

    [2] => Array
        (
            [id] => 4bf58dd8d48988d16c941735
            [name] => Burger Joint
            [pluralName] => Burger Joints
            [shortName] => Burgers
        )

    [3] => Array
        (
            [id] => 4bf58dd8d48988d14e941735
            [name] => American Restaurant
            [pluralName] => American Restaurants
            [shortName] => American
        )
)

Or maybe its easier to do another function if this array already exists, just delete some values to output a new array?

Thanks!

1 Answer 1

1

Try array_unique php function that will help.

Also Try

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

echo "<pre>";
print_r($unique);
echo "</pre>";

Above code is tested.

Complete Tested Code

<?php
$array = array
(
    '0' => array
    (
        'id' => '4bf58dd8d48988d16c941735',
        'name' => 'Burger Joint',
        'pluralName' => 'Burger Joints',
        'shortName' => 'Burgers'
    ),
    '1' => array
    (
        'id' => '4bf58dd8d48988d16c941735',
        'name' => 'Burger Joint',
        'pluralName' => 'Burger Joints',
        'shortName' => 'Burgers'
    ),
    '2' => array
    (
        'id' => '4bf58dd8d48988d16c941735',
        'name' => 'Burger Joint',
        'pluralName' => 'Burger Joints',
        'shortName' => 'Burgers'
    ),
    '3' => array
    (
        'id' => '4bf58dd8d48988d14e941735',
        'name' => 'American Restaurant',
        'pluralName' => 'American Restaurants',
        'shortName' => 'American'
    )
);

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

echo "<pre>";
print_r($unique);
?>

Cheers.

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

1 Comment

i have updated my answer please take a look, i have also tested it.

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.