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?

4
  • 5
    You should show the "many ways" that you have tried. You should also show what the expected result is from the above sample. Commented May 22, 2018 at 20:43
  • you can look at stackoverflow.com/questions/4260086/… Commented May 22, 2018 at 20:47
  • 1
    Possible duplicate of PHP: How to use array_filter() to filter array keys? Commented May 22, 2018 at 21:06
  • @PseudoAj How is that related? This is an indexed array, not an associative array. Commented May 22, 2018 at 21:28

1 Answer 1

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.

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

2 Comments

You need to add use($conditions) to the function so that it can access the variable.
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!

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.