Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 808
Томица Кораћ Avatar asked Aug 06 '26 22:08

Томица Кораћ


1 Answers

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
like image 123
Amadan Avatar answered Aug 08 '26 12:08

Amadan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!