0

I want to avoid if it is possible foreach combined with if. I want to search the array, take out the matches and create new one base on result.

In this example I want to create separate arrays for each os -

$os1 = $array;
$os2 = $array...

Array looks like this:

    $array = [
            0 => [
                'id'   => 1,
                'name' => 'name',
                'os'   => 1
            ],
            1 => [
                'id'   => 2,
                'name' => 'name',
                'os'   => 1
            ],
            2 => [
                'id'   => 3,
                'name' => 'name',
                'os'   => 2
            ],
            3 => [
                'id'   => 3,
                'name' => 'name',
                'os'   => 2             
            ]
    ];
3
  • why do you want to avoid foreach? - also try to re-write your question without using 'for each' ;) Commented Mar 13, 2015 at 13:42
  • I think you can use the function array_map Commented Mar 13, 2015 at 13:47
  • What is your desired output? Commented Mar 13, 2015 at 13:52

2 Answers 2

2

Use array_filter to reduce the input array to the expected result

$os = 1;
$data = array_filter($array, function($item) use ($os) {
    return $item['os'] == $os;
});
Sign up to request clarification or add additional context in comments.

Comments

0

The short one

$os1 = [];
$os2 = [];
$os3 = [];

foreach ($array as $item) {
    ${'os' . $item['os']}[] = array('id' => $item['id'], 'name' => $item[$name];
}

The better one

$os1 = [];
$os2 = [];
$os3 = [];

foreach ($array as $item) {
    switch($item['os']) {
        case 1:
            $os1[] = array('id' => $item['id'], 'name' => $item[$name]);
            break;
        case 2:
            $os2[] = array('id' => $item['id'], 'name' => $item[$name]);
            break;
        case 3:
            $os3[] = array('id' => $item['id'], 'name' => $item[$name]);
            break;
        default:
            throw new Exception('Unknown Os');
    }
}

Also you maybe want to assign array($item['id'] => $item[$name]); instead of array('id' => $item['id'], 'name' => $item[$name]);

$os1 = [];
$os2 = [];
$os3 = [];

foreach ($array as $item) {
    ${'os' . $item['os']}[] = array($item['id'] => $item[$name]);
}

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.