1

I have a multi dimensional array. I need to search through the arrays and retrieve instance of dates that match each other.

This is my array:

$dateArray = array(8) {
  [0]=>
  array(15) {
    ["bookable_id"]=>
    string(1) "1"
    ["event_date"]=>
    string(10) "2019-09-11"

  }
  [1]=>
  array(15) {
    ["bookable_id"]=>
    string(1) "1"
    ["event_date"]=>
    string(10) "2019-09-11"
  }
  [2]=>
  array(15) {
    ["bookable_id"]=>
    string(1) "4"
    ["event_date"]=>
    string(10) "2019-10-17"
  }
  [3]=>
  array(15) {
    ["bookable_id"]=>
    string(1) "4"
    ["event_date"]=>
    string(10) "2019-10-17"

  }
  [4]=>
  array(15) {
    ["bookable_id"]=>
    string(1) "3"
    ["event_date"]=>
    string(10) "2020-09-15"

  }
  [5]=>
  array(15) {
    ["bookable_id"]=>
    string(1) "3"
    ["event_date"]=>
    string(10) "2020-09-15"
  }
  [6]=>
  array(15) {
    ["bookable_id"]=>
    string(1) "2"
    ["event_date"]=>
    string(10) "2021-09-09"
  }
}

This is my function:

function searchMatchingDates($compare, $array)
    {
        foreach ($array as  $val) {
            if ($compare["event_date"]== $val["event_date"]){
                return $val;
            }
        }
        return null;

And this is how i searched it:

foreach ($dateArray as $compare) {

 $match  = searchMatchingDates($compare, $array); 

}

if($match){

echo "$compare['bookable_id'] + $match['bookable_id']; "

}

This works and return the date. It however return duplicate dates as the array will compare twice.

I need a way to remove an array once an array has been compared once .

For example, once array once has ran its iteration it needs to be removed so that the next array does not do a comparison on it.

Paul Kendal
  • 559
  • 9
  • 24
  • remove duplicate values from your array:- https://stackoverflow.com/questions/307674/how-to-remove-duplicate-values-from-a-multi-dimensional-array-in-php – Alive to die - Anant Sep 11 '19 at 13:11

1 Answers1

0

If I understand the question, you want to return the dates which feature more than once in the array?

You could do this by counting all of those which feature more than once (array_count_values() https://www.php.net/manual/en/function.array-count-values.php combined with array_column()), then filtering the array based on that outcome.

// get dates which feature more than once
$dateCounts = array_filter(
    array_count_values(array_column($dateArray, 'event_date')),
    function ($count) {
        return $count > 1;
    }
);

// filter those matching dates
$matching = array_filter($dateArray, function ($date) use ($dateCounts) {
    return isset($dateCounts[$date['event_date']]);
});

var_dump($matching);
benJ
  • 2,442
  • 1
  • 18
  • 16