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)

3
  • foreach, there is no anything built-in for that Commented May 28, 2012 at 20:19
  • How is your array constructed? You may be better off changing that. Commented May 28, 2012 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. Commented May 29, 2012 at 5:35

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

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

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.