0

I have the following array:

array(3) {
  [0]=>
  array(2) {
    ["label"]=> string(10) "Chardonnay"
    ["value"]=> int(245)
  }
  [1]=>
  array(2) {
    ["label"]=> string(10) "Chardonnay"
    ["value"]=> int(33)
  }
  [2]=>
  array(2) {
    ["label"]=> string(10) "Chardonnay"
    ["value"]=>int(175)
  }
  [3]=>
  array(2) {
    ["label"]=> string(10) "Stein"
    ["value"]=>int(195)
  }
}

How would I go about "filtering" this array so that it looks like this:

array(2) {
  [0]=>
  array(2) {
    ["label"]=> string(5) "Chardonnay"
    ["value"]=> int(245)
  }
  [1]=>
  array(2) {
    ["label"]=> string(10) "Stein"
    ["value"]=>int(195)
  }
}

So in essence, I want to remove array elements by value where the value is not unique.

I don't even know where to start. Please assist?

2
  • What's the logic behind keeping the one with 245? Commented May 12, 2020 at 14:00
  • @AbraCadaver Just happens to be the first one in the array of duplicates. In the end the site will simply display "Active Filters: Chardonnay, Stein" Commented May 12, 2020 at 14:02

2 Answers 2

2

Since keys must be unique, you can index on the label and you will only have one of each:

$result = array_column($array, null, 'label');

If you just want a single dimension with unique values, extract all labels and then make it unique:

$result = array_unique(array_column($array, 'label'));

If this array is coming from a database query then you would do it in the query instead.

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

2 Comments

Perfect mate, thanks. Will mark as correct as soon as the timer allows me.
Try both, the second one may give you something easier to work with if you don't need the value keys.
1

You can use this code:

<?php

$arr = [
    [
        "label"=> "Chardonnay",
        "value"=> 245,
    ],
    [
        "label"=> "Chardonnay",
        "value"=> 33,
    ],
    [
        "label"=> "Chardonnay",
        "value"=> 75,
    ],
    [
        "label"=> "Stein",
        "value"=> 195,
    ],
];


$arr = array_intersect_key($arr,array_unique(array_column($arr,'label')));
print_r($arr);

It will remove duplicates, then intersect the keys (0,3 in this case) with the original array. An alternative to preserve the original keys.

Comments

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.