0

I have to filter an array for PrestaShop. I have some raw data, but I have to filter this. So I have some inputs for search in raw data and I try in many ways but my boss still says there is a better way. I don't get this so I need help.

<?php 
// Raw data
$data = array(
    array('id' => 1, 'name' => "Andrei", "time" => 3),
    array('id' => 5, 'name' => "David", "time" => 62),
    array('id' => 8, 'name' => "Igor", "time" => 12),
    array('id' => 4, 'name' => "Jack", "time" => 3),
);
// These are condition for filter my $data 
// In this condition i want filter my $data by name and time
$conditions = array('id' => null, 'name' => "David", 'time' => "3");
?>

The question is what is the best way or method for filter for all combination of my $condition?

Alessio Cantarella
  • 5,077
  • 3
  • 27
  • 34
  • 5
    You should show the "many ways" that you have tried. You should also show what the expected result is from the above sample. – Patrick Q May 22 '18 at 20:43
  • you can look at https://stackoverflow.com/questions/4260086/php-how-to-use-array-filter-to-filter-array-keys – burhangok May 22 '18 at 20:47
  • 1
    Possible duplicate of [PHP: How to use array\_filter() to filter array keys?](https://stackoverflow.com/questions/4260086/php-how-to-use-array-filter-to-filter-array-keys) – PseudoAj May 22 '18 at 21:06
  • @PseudoAj How is that related? This is an indexed array, not an associative array. – Barmar May 22 '18 at 21:28

1 Answers1

2

You should look into array_filter using a callback.

array_filter($data, function ($item) use ($conditions) {
    return $item['id'] === $conditions['id'] || $item['name'] === $conditions['name'] || $item['time'] === $conditions['time'];
}

You will want to tweak the return's verification depending on your intended filtering.

Jeremy Dentel
  • 837
  • 2
  • 9
  • 19
  • 1
    You need to add `use($conditions)` to the function so that it can access the variable. – Barmar May 22 '18 at 21:27
  • It’s been a solid while since I have used PHP (mostly a JavaScript developer now) and I always forgot to do that, even when I was actively using it. Thanks! – Jeremy Dentel May 22 '18 at 21:29