chris
chris

Reputation: 36937

PHP multidimensional array compare nested array items and leave only unique ones

Ok I have an multidimensional array

Array(
    [items] [0] array(
             [0] array("name"=>"something", "price"=>"0.00", "desc"=>"blah blah blah"),
             [1] array("name"=>"other", "price"=>"0.00", "desc"=>"blah blah blah"),
             [2] array("name"=>"monkey", "price"=>"0.00", "desc"=>"blah blah blah"),
             [3] array("name"=>"something", "price"=>"0.00", "desc"=>"blah blah blah"),
             [4] array("name"=>"suit", "price"=>"0.00", "desc"=>"blah blah blah")
    ),
    [categories] [0] array("outter", "inner", "summer", "fall"),
    [subcategories] [0] array("outter", "inner", "summer", "fall")
)

(ok its a poor hand typed rendition but you get the idea). What My concern is, is the "items" if there is more than one name thats the same I want to remove that entry, but Im really not sure how I would go about achieving this properly without concocting some large ugly set up loops. So I am trying to get some help coming up with something thats fast, optimized, and well cleaner than what I am likely to come up with for an idea.

Upvotes: 0

Views: 333

Answers (1)

rjz
rjz

Reputation: 16510

OK, it's one loop. But what about switching the array out temporarily for an associative one and pulling the values?

$assoc_items = array();

foreach($items as $item) {
  $assoc_items[$item['name']] = $item;
}

$result = array_values($assoc_items);

result now contains a list of the items from $items with unique names.

Upvotes: 1

Related Questions