0

So I have some code looking like this at the moment:

    $filter = new \stdClass();

    $queryObj = $this->getpost['filter'];

    $filters = new \stdClass();
    $filters->team = $queryObj['team'];
    $filters->skill = $queryObj['skill'];
    $filters->division = $queryObj['division'];

    $filter->filters = $filters;
    $users = $managerStatistics->getManagerDeliveryData($filter);

I fellt the need to do this because in the getManagerDeliveryData(§filter), there is a "foreach $filter->filters"..

Does anyone know how to do this in a better looking way? This looks messy to me but I'm not sure what to do here..

1
  • What exactly looks messy to you here? Commented Jul 9, 2020 at 18:56

2 Answers 2

2

You could rewrite the way you build the data into a more compact format, casting each array definition to an object as needed...

$filter = (object) [
        "filters" => (object) [ 'team' => $queryObj['team'], 
                'skill' => $queryObj['skill'], 
                'division' => $queryObj['division'] ]
];
Sign up to request clarification or add additional context in comments.

1 Comment

This is what I'm talking about, wonder when these things will start coming naturally :(
0

If you cast an associative array to an object, it becomes a stdClass object with matching properties. Here's a generic example:

$arr = ['one' => 'foo', 'two' => 'bar', 'three' => 'meh']; 
$obj = (object) $arr;   

var_dump($obj);

This would give you:

object(stdClass)#2 (3) {
    ["one"] · string(3) "foo"
    ["two"] · string(3) "bar"
    ["three"] · string(3) "meh"
}

In your case, you could do the following, if you're hoping to not have to name your $queryObj keys/values one by one (which is necessary if e.g. the filter list isn't fixed, and therefore can't be hard-coded):

$filters = (object) $queryObj;

Obviously, every key/value pair in the source array then becomes a property/value pair in the object. If there are particular values you want to omit, either unset them or use array_intersect_key() etc. functions to only cast the desired keys. Suppose your $queryObject had a bunch of keys, but you only wanted the ones in your example, you could do this:

$keymap = ['team', 'skill', 'division'];
$filters = (object) array_intersect_key(array_flip($keymap), $queryObject);

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.