1

how do you chunk array like this below?

array(
[0] => array(
    ['id'] => '1',
    ['parent_id'] => ''
)
[1] => array(
    ['id'] => '2',
    ['parent_id'] => ''
)
[2] => array(
    ['id'] => '3',
    ['parent_id'] => '1'
)
[3] => array(
    ['id'] => '3',
    ['parent_id'] => '1'
)
[4] => array(
    ['id'] => '3',
    ['parent_id'] => '2'
)
)

I'd like to group subelements (with specified parent_id) to do a separate foreach.

2
  • you have reconstruct your array by placing the sub elements under a tree of a parent_id it self Commented Jul 17, 2013 at 8:56
  • one option is to walk through the array with foreach and create a new array manually depending on the current sub-array values. Commented Jul 17, 2013 at 8:57

1 Answer 1

4

You can do a simple foreach and rearrange the array.

$result = array();
foreach ($arr as $element) {
  $result[$element['parent_id']][] = $element;
}

http://phpfiddle.org/main/code/3ar-ixg

Sign up to request clarification or add additional context in comments.

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.