Item reallocation in array key

1

Good afternoon! Although I have researched the subject and searched the documentation, I still can not come up with a solution to the following problem .. I have an array brought from the bank with titles and items.

The array looks like this:

$a[0] = [
    "titulo" => "titulo1",
    "item" => "item 1",
];
$a[1] = [
    "titulo" => "titulo 2",
    "item" => "item 2",
];
$a[2] = [
    "titulo" => "titulo 2",
    "item" => "item 3",
];

My goal is to turn this array into a new one, with items already reallocated, eg:

$limpo[0] = [
    "titulo" => "titulo1",
    "item" => "item 1",
];
$limpo[1] = [
    "titulo" => "titulo 2",
    "item" => "item 2",
    "item" => "item 3,
];

In other words, titles will not be repeated.

So far, I've put the code as follows ..

foreach ($a as $key => $value) {

    if($key>0){
        $comparacao = ($a[$key-1]["titulo"]);   
        echo($comparacao."<br>");
    }

    if($key==0){
    $limpo[$key] = [
        "titulo" => $value['titulo'],
        "item" => $value['item']
    ];
    }else if($value["titulo"] != $comparacao){
        $limpo[$key] = [
        "titulo" => $value['titulo'],
        "item" => $value['item']
    ];
    }
    else if($value["titulo"] == $comparacao){

        //array_push($limpo[($key-1)]['item'], $value['item']);

        $limpo[($key-1)] = [
        "titulo" => $value['titulo'],
        "item" => $value['item']
    ];
    }
}

However, at the moment it falls in ($value["titulo"] == $comparacao) , "item 3" is allocated in place of item 2, being as follows:

$limpo[0] = [
    "titulo" => "titulo1",
    "item" => "item 1",
];
$limpo[1] = [
    "titulo" => "titulo 2",
    "item" => "item 3",
];

Would you have any way to push in the previous position? The commented push snippet is returning an error because it indicates the previous position.

Hugs.

    
asked by anonymous 24.09.2018 / 22:34

1 answer

1

You can use the title as array index since they are unique. So it's easy to test if the title already exists. If it exists add the item to an array, otherwise create the title. Ex.:

<?php

$limpo = [];

foreach ($array as $a) {
    $titulo = $a["titulo"];

    if (! isset($limpo[$titulo])) {
        $limpo[$titulo] = [
            "titulo" => $a["titulo"],
            "item" => [ $a["item"] ],  // cria uma array de items
        ];
    } else {
        $limpo[$titulo]["item"][] = $a["item"];  // adiciona item ao array
    }
}

/* print:

    [
    'titulo 1' => [
        'titulo' => 'titulo 1',
        'item' => ['item 1']
    ],
    'titulo 2' => [
        'titulo' => 'titulo 2',
        'item' => ['item 2', 'item 3']
    ]
]

*/

Working Code ...

    
24.09.2018 / 22:54