Томица Кораћ
Томица Кораћ

Reputation: 2662

PHP - Divide a multidimensional array depending on a field's value

I have an initial array:

$arr0 = array(
    0 => array(
        'a' => 1,
        'b' => 1
    )
    1 => array(
        'a' => 2,
        'b' => 1
    )
    2 => array(
        'a' => 3,
        'b' => 2
    )
    3 => array(
        'a' => 4,
        'b' => 3
    )
    4 => array(
        'a' => 5,
        'b' => 3
    )
);

I wish to divide it into separate arrays depending on its members' value of the field 'b', like so:

// $arr1 contains $arr0[0] and $arr0[1] because their value of 'b' is 1.
$arr1 = array(
    0 => array(
        'a' => 1,
        'b' => 1
    )
    1 => array(
        'a' => 2,
        'b' => 1
    )
);

// $arr2 contains $arr0[2] because its value of 'b' is 2.
$arr2 = array(
    0 => array(
        'a' => 3,
        'b' => 2
    )
);

// $arr3 contains $arr0[3] and $arr0[4] because their value of 'b' is 3.
$arr3 = array(
    0 => array(
        'a' => 4,
        'b' => 3
    )
    1 => array(
        'a' => 5,
        'b' => 3
    )
);

Now, the field 'b' can have any natural number for value, so it is not always three resulting arrays that I will need.

I have found a related question (and answers) here, but my problem is specific because I don't know in advance what original values 'b' has, and how many of different values there are.

Any ideas?

(edit: $arr3 was written as $arr1)

Upvotes: 3

Views: 3802

Answers (2)

Amadan
Amadan

Reputation: 198324

foreach ($arr0 as $value) {
  ${"arr" . $value['b']}[] = $value;
}
// $arr1, $arr2 and $arr3 are defined

There is magic in the second line, which dynamically builds a variable name. However, that way of programming is really unwieldy; you would do better to make the results into yet another array, like this:

foreach ($arr0 as $value) {
  $allarr[$value['b']][] = $value;
}
// $allarr is defined

Upvotes: 7

Jeroen
Jeroen

Reputation: 13257

foreach ($arr0 as $val) {
    $b = $val ['b'];
    if (!$arr$b) $arr$b = array();
    $arr$b[] = $val;
}

Upvotes: 1

Related Questions