Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I want to be able to take an array of stdClass returned from PDO fetchAll and turn this into a single array.

So i get an array back that looks like this:

// print_r($getCategories); returns..

        Array
    (
        [0] => stdClass Object
            (
                [field1] => 'foo',
                [field2] => 'foo2'
            )

        [1] => stdClass Object
            (
                [field1] => 'bar'
                [field2] => 'bar2'
            )
    )

I loop through this and put a list of one field into a combo box

// <select> and <option> around this..

    foreach($getCategories as $category) {

        echo $category->field1;

    }

Now i know i could create an array by using the following code

foreach($getCategories as $category){

    if($_POST['category'] == $category->field1){

        $chosenCategory = array(

            'field1' => $category->field1,
            'field2' => $category->field2

        );

    }

}

I just want to know if there is a better way to do this where I don't have to build an array, instead just filter what is returned in $getCategories using user input?

I am fairly new to OOP and programming in general so an explanation as well as an answer would be much appreciated!

Thanks

share|improve this question
    
Doesn't PDO::fetchAll return an array by default? –  Jonathan Kuhn Mar 13 at 17:04
    
Untested: $categories = array_walk( $categories, function (&$value) { $value = (array) $value; } ); –  Mark Baker Mar 13 at 17:05
    
Yes it does return an array but an array of stdClass objects. I need to filter these down to a single object or an array as shown above with the same keys. –  MrRiceman Mar 13 at 17:23
    
Ok thanks so that would set $categories to an array of categories (which are arrays themselves). How would i then filter this down to get the array which contains the value i have? –  MrRiceman Mar 13 at 17:27
    
See fetch_style in Manual –  david strachan Mar 13 at 17:37

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.