0

I am trying to filter an array which will produce a drill down list. This array is built from JSON.

My array looks like this

Array
(
    [0] => Array
        (
            [make] => somemake
            [model] => somemodel
            [variant] => somevariant
            [fuel] => somefuel
            [vehicle] => somedetailedinfo
        )
    [1] => Array
        (
            [make] => somemake
            [model] => somemodel1
            [variant] => somevariant1
            [fuel] => somefuel1
            [vehicle] => somedetailedinfo
        )
     [2] => Array
        (
            [make] => somemake
            [model] => somemodel2
            [variant] => somevariant2
            [fuel] => somefuel
            [vehicle] => somedetailedinfo
        )
    [3] => Array
        (
            [make] => somemake1
            [model] => somemodel3
            [variant] => somevariant3
            [fuel] => somefuel1
            [vehicle] => somedetailedinfo
        )

)

I would like to filter this array by the make $make, which is set by the $_SERVER['QUERY_STRING'].

The new array should contain all items with the make $make.

How do I do this using array_filter?

1 Answer 1

1

This is fairly straight-forward. Note that null coalesce (??) is >= 7.0.

$make = $_GET['make'] ?? 'Chevy';
$vehicles = [[
    'make' => 'Ford',
    'model' => 'F-150',
    'variant' => '4x4',
    'fuel' => 'diesel',
    'vehicle' => [range(1,3)],
],[
    'make' => 'Ford',
    'model' => 'Escort',
    'variant' => 'XS',
    'fuel' => 'gas',
    'vehicle' => [range(1,3)],
],[
    'make' => 'Chevy',
    'model' => 'Cobalt',
    'variant' => 'ES',
    'fuel' => 'electric',
    'vehicle' => [range(1,3)],
],[
    'make' => 'Ford',
    'model' => 'Explorer',
    'variant' => '2x4',
    'fuel' => 'gas',
    'vehicle' => [range(1,3)],
],[
    'make' => 'Mini',
    'model' => 'Cooper',
    'variant' => 'eTurbo',
    'fuel' => 'electro-diesel',
    'vehicle' => [range(1,3)],
],];

print_r(array_filter($vehicles, function($vehicle) use($make) {
    return $vehicle['make'] === $make;
}));

Gives:

Array
(
    [2] => Array
        (
            [make] => Chevy
            [model] => Cobalt
            [variant] => ES
            [fuel] => electric
            [vehicle] => Array
                (
                    [0] => Array
                        (
                            [0] => 1
                            [1] => 2
                            [2] => 3
                        )
                )
        )
)

https://3v4l.org/B8T6v

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

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.