0

I need some help with this array I can't figure out how can I create a multidimensional array according to some array values.

I have a normal array, let's say with the following dump output:

array(
  [0] => ("id" => "421", "name" => "element 1", "TYPE" => "1")
  [1] => ("id" => "422", "name" => "element 2", "TYPE" => "2")
  [2] => ("id" => "423", "name" => "element 3", "TYPE" => "2")
  [3] => ("id" => "424", "name" => "element 4","TYPE" => "1")
)

I need to create a multidimensional array according to "TYPE" key. if TYPE = 1 this array should contain all arrays which have "TYPE" == 2 until the next array will be found with the TYPE == 1 the output should be something like this:

array(
  [421] => array(
    "column" => array("id" => "421", "name" => "element 1", "TYPE" => "1"),
    "subcolumns" => array(
        [0] => ("id" => "422", "name" => "element 2", "TYPE" => "2"),
        [1] => ("id" => "423", "name" => "element 3","TYPE" => "2")
     )
  )
  [424] => array(
    "column" => array("id" => "424", "name" => "element 4","TYPE" => "1"),
    "subcolumns" => array()
  )
)

Any ideas if I can accomplish this task with twig (it will be much better for me), if not, I am ok with PHP too. I have already tried to construct the HTML structure without changing the array but with no success.

I need to create columns and the "parent" should be the item with Type 1, all items with TYPE 2 should be childs of TYPE 1, in order to use jquery ui to sort them left and right.

Thank you!

5
  • 1
    Twig is a template engine, it's purpose to output data, not process it in anyway. Commented Mar 8, 2018 at 14:27
  • And second - what's the problem with iterating over array and rebuild it? Commented Mar 8, 2018 at 14:27
  • I don't know how to rebuild it. Commented Mar 8, 2018 at 14:30
  • 1
    Have you tried anything or just wating for codes? Commented Mar 8, 2018 at 14:31
  • I tried a lot in twig, that's why I first asked in twig and the in php. I come to ask here only when I can not find anything on google. Commented Mar 8, 2018 at 14:36

1 Answer 1

2

Some code to start with:

$new_array = [];
$cur_id = 0;
foreach ($array as $item) {
    if ($item['TYPE'] == 1) {
        $new_array[$item['id']] = [
            'column' => $item,
            'subcolumns' => [],
        ];
        $cur_id = $item['id'];
    } else {
        $new_array[$cur_id]['subcolumns'][] = $item;
    }
}
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.