1

I have an array that looks like this:

MyArray (
    [0] => Array (
                            [board_id] => 1047999
                            [added_date] => 2013-02-28 11:14:02
                            [type] => 4
                           )
    [1] => Array (
                           [board_id] => 1047999
                           [added_date] => 2013-02-28 11:14:02
                           [type] => 1
                          )
    [2] => Array (
                          [board_id] => 1047999
                          [added_date] => 2013-02-28 11:14:02
                          [type] => 4
                          )
    [3] => Array (
                          [board_id] => 1047999
                          [added_date] => 2013-02-28 11:14:02
                          [type] => 1
                          )
)

How can I split this array by type and keep the exact same array structure? I.e. I would have MyArrayT4 with two subarrays, and MyArrayT1 with two subarrays?

TIA!

1
  • the last entry, is there [3] => Array(missing?? Commented Mar 3, 2013 at 21:15

1 Answer 1

2

use array_filter like this EDIT use array_values to reset

$filtering = function($type) use($your_array) {
    $filtered = array_filter($your_array, function($r) use($type) {
        return $r['type'] == $type;
    });

    return array_values($filtered);
};


$array_1 = $filtering->__invoke('4');
$array_2 = $filtering->__invoke('1');
Sign up to request clarification or add additional context in comments.

5 Comments

Wouldn't it be better to pass the input array as a parameter instead of use? Also the __invoke is unnecessary $filtering() is enough.
I had no idea you could do javascript-style var = function() {} instructions in PHP. That's awesome.
@AustinMullins Closures are supported since PHP 5.3 ... yea... you can pass the array..
Thanks silly. You may want to add in your answer that one should use array_values to reset the array numbering, otherwise loops can get messed up!
Wanted to post a response, saw this and hit pause. Great one.

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.