3

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)

Community
  • 1
  • 1
Томица Кораћ
  • 2,542
  • 7
  • 35
  • 57
  • `foreach`, there is no anything built-in for that – zerkms May 28 '12 at 20:19
  • How is your array constructed? You may be better off changing that. – vascowhite May 28 '12 at 21:11
  • My array is result of a Database query, where $arr[0], $arr[1] etc. are table rows. Fields 'a' and 'b' are DB fields 'content_type' and 'content_unit' respectively. I need to echo the value of a third DB field depending if it belongs to a specified type and a specified unit, but also all the content that belongs to a specified type only, and all the content that belongs to a specified unit only. – Томица Кораћ May 29 '12 at 05:35

2 Answers2

7
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
Amadan
  • 191,408
  • 23
  • 240
  • 301
1
foreach ($arr0 as $val) {
    $b = $val ['b'];
    if (!$arr$b) $arr$b = array();
    $arr$b[] = $val;
}
Jeroen
  • 13,056
  • 4
  • 42
  • 63